-
-
Save ginpei/dac4c4a190d29dde9118c3e811c4e337 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface FruitMap { | |
'Apple': AppleFruit; | |
'Banana': BananaFruit; | |
} | |
type FruitName = keyof FruitMap; | |
type Fruit = FruitMap[FruitName] | |
interface FruitBase<Type extends FruitName> { | |
type: Type | |
} | |
interface AppleFruit extends FruitBase<'Apple'> { | |
sliced: boolean; | |
peeled: boolean; | |
} | |
interface BananaFruit extends FruitBase<'Banana'> { | |
color: 'yellow' | 'green'; | |
} | |
function createFruitOf<T extends FruitName>(type: T): FruitMap[T] { | |
if (type === 'Apple') { | |
const apple: AppleFruit = { | |
peeled: false, | |
sliced: false, | |
type: 'Apple', | |
}; | |
return apple as any; | |
} | |
if (type === 'Banana') { | |
const banana: BananaFruit = { | |
color: 'green', | |
type: 'Banana', | |
}; | |
return banana as any; | |
} | |
throw new Error(`Unknown type "${type}"`); | |
} | |
const apple = createFruitOf('Apple'); | |
const banana = createFruitOf('Banana'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment