如何在类型构造函数中使用可选类型参数?下面,我希望 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' };
最佳答案
我认为我可以使用带有 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 }; // √
关于javascript - 流可选类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48871045/