Skip to content

Instantly share code, notes, and snippets.

@ginpei
Created June 22, 2020 00:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ginpei/b34a4533829a524241b0f43fea7c7a6c to your computer and use it in GitHub Desktop.
Save ginpei/b34a4533829a524241b0f43fea7c7a6c to your computer and use it in GitHub Desktop.
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