Skip to content

Instantly share code, notes, and snippets.

@ginpei
Created June 22, 2020 05:33
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/dac4c4a190d29dde9118c3e811c4e337 to your computer and use it in GitHub Desktop.
Save ginpei/dac4c4a190d29dde9118c3e811c4e337 to your computer and use it in GitHub Desktop.
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