如何在类型构造函数中使用可选的类型参数?在下面,我希望Fruit
类型构造函数根据是否传递C
返回不同的类型:
type Color =
| 'yellow'
| 'orange'
| 'red';
type Fruit<T, C> = {
// ^ I wanna make this optional
t: T,
color: C, // <- should be optional if there's no C
};
type Orange = Fruit<'orange', Color>
type Apple = Fruit<'apple'>;
// √
const orange: Orange = { t: 'orange', color: 'orange' };
// Error: Cannot use `Apple` with less than 2 type arguments.
const apple: Apple = { t: 'apple' };
答案 0 :(得分:2)
我认为我可以使用empty
的默认类型来完成此操作,但我不确定它是否是最佳方式:
type Color =
| 'yellow'
| 'orange'
| 'red';
type Fruit<T, C = empty> = {
t: T,
color?: C,
};
type Orange = Fruit<'orange', Color>
type Apple = Fruit<'apple'>;
type Banana = Fruit<'banana', number>;
const orange: Orange = { t: 'orange', color: 'orange' }; // √
const apple: Apple = { t: 'apple' }; // √
const banana: Banana = { t: 'banana', color: 1 }; // √