So what is the difference between combining two types or interfaces, using '&' and using '|'.
See Naming of TypeScript's union and intersection types:
type Dog = { breed: string; }; // Intersection type Bulldog = { isCute: boolean; } & Dog; const winston: Bulldog = { breed: 'Bulldog', isCute: false, }; // Union type Pet = { name: string } | Dog; const cat: Pet = { name: 'Fluffykins' }; const fido: Pet = { name: 'froufrou', breed: 'Maltese' }; const dog: Pet = { breed: 'Boston Terrier' }
intersection of types (&): the shape of the data has to conform to the constraints of all the intersected types simultaneously.
&
union of types (|): the shape of the data has to conform to the constraints of at least one of the unioned types.
|
thank you for explaining along with code snippets.....appreciate it!!
isCute: false, but Winston IS cute :( (lol just being silly. Thank you for the further clarification/doc resrouce)
isCute: false,
The & will merge the types, so all the properties of both types will be in the resulting type.
The | will give you the option to choose between all the given types, and use one of them, rather than all together :)
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
So what is the difference between combining two types or interfaces, using '&' and using '|'.
See Naming of TypeScript's union and intersection types:
intersection of types (
&
): the shape of the data has to conform to the constraints of all the intersected types simultaneously.union of types (
|
): the shape of the data has to conform to the constraints of at least one of the unioned types.thank you for explaining along with code snippets.....appreciate it!!
isCute: false,
but Winston IS cute :((lol just being silly. Thank you for the further clarification/doc resrouce)
The & will merge the types, so all the properties of both types will be in the resulting type.
The | will give you the option to choose between all the given types, and use one of them, rather than all together :)