简体   繁体   中英

flow optional type parameter

How can I use an optional type parameter in a type constructor? In the following, I want the Fruit type constructor to return different types based on whether C is passed or not:

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' }; 

I think I can use default types with empty to accomplish this, but I'm not sure if it's the best way:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM