Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
143
rated 0 times [  146] [ 3]  / answers: 1 / hits: 16458  / 7 Years ago, fri, march 3, 2017, 12:00:00
type someType = {
keyOne: string,
keyTwo: string,
};

type someOtherType = {
keyOne: string,
keyTwo: string,
keyThree: string,
};


Both of these types are objects that contain keyOne and keyTwo, the only difference is the latter extends the former with an additional key of keyThree.



Rather than writing duplicated code, is it possible to build the someOtherType flow type by extending someType? In my mind, ES6 object rest/spread comes to mind, but I'm not sure how to accomplish something like this in Flow.



Thanks!


More From » casting

 Answers
22

What you're looking for is the intersection type. According to the documentation:



An intersection type requires a value to be all of the input types.


Syntax: Intersection: < type 1 > & < type 2 > ... & < type n >



The intersection type is intended to extend an existing type and add additional type requirements to it.


type someType = {
keyOne: string,
keyTwo: string
}

type someOtherType = someType & {
keyThree: string
}

const shouldBeOk: someOtherType = {
keyOne: 'biz',
keyTwo: 'buzz',
keyThree: 'baz',
}

const shouldError: someOtherType = {
keyOne: 123,
keyTwo: 'hello',
keyThree: 'world',
}

// flow error:
16: const shouldError: someOtherType = {
^ object literal. This type is incompatible with
8: type someOtherType = someType & {
^ object type

The logical opposite of the intersection type is the union type. According to the documentation:



A union type requires for a value to be one of the input types.


Syntax: Union: < type 1 > | < type 2 > ... | < type n >



As an example. you can use the union type to create an enumerable.


type fooBarBazType = 'foo' | 'bar' | 'baz';
const shouldBeOk: fooBarBazType = 'bar';

const shouldError: fooBarBazType = 'buzz';

4: const shouldError: fooBarBazType = 'buzz';
^ string. This type is incompatible with
4: const shouldError: fooBarBazType = 'buzz';
^ string enum

[#58686] Wednesday, March 1, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
micayla

Total Points: 148
Total Questions: 92
Total Answers: 109

Location: Aruba
Member since Sat, Oct 2, 2021
3 Years ago
micayla questions
Fri, Dec 24, 21, 00:00, 2 Years ago
Thu, Apr 16, 20, 00:00, 4 Years ago
Thu, Nov 14, 19, 00:00, 5 Years ago
;