flow可选类型参数

时间:2018-02-19 17:16:02

标签: javascript generics flowtype parameterized-types type-constructor

如何在类型构造函数中使用可选的类型参数?在下面,我希望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' }; 

1 个答案:

答案 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 };        // √