-
-
Save ginpei/b34a4533829a524241b0f43fea7c7a6c to your computer and use it in GitHub Desktop.
This file contains 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
type FruitTemplate<Type extends string, Props> ={ type: Type } & Props | |
type Fruit = | |
| AppleFruit | |
| BananaFruit | |
type AppleFruit = FruitTemplate<'Apple', { | |
sliced: boolean; | |
peeled: boolean; | |
}> | |
type BananaFruit = FruitTemplate<'Banana', { | |
color: 'yellow' | 'green'; | |
}> | |
function createFruitOf<T extends Fruit['type']>(type: T) { | |
if (type === 'Apple') { | |
const apple: AppleFruit = { | |
peeled: false, | |
sliced: false, | |
type: 'Apple', | |
}; | |
return apple; | |
} | |
if (type === 'Banana') { | |
const banana: BananaFruit = { | |
color: 'green', | |
type: 'Banana', | |
}; | |
return banana; | |
} | |
throw new Error(`Unknown type "${type}"`); | |
} | |
const apple = createFruitOf('Apple'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment