Sam R.
Sam R.

Reputation: 16450

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

Upvotes: 2

Views: 1591

Answers (1)

Sam R.
Sam R.

Reputation: 16450

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

Upvotes: 3

Related Questions