TypeScript Operator Type Usage
1. Union Type
New type created by combining two or more types
Uses
|operator, like JavaScript's || (OR) operator, meaning "A or B" type (e.g.number | string: number or string type)When defining
valueparameter type asanyand outputting with if-else statement according to whether type isnumberorstringfunction printValue(value: any): void { if (typeof value === 'number') { console.log(`The value is a number: ${value}`); } else { console.log(`The value is a string: ${value}`); } } printValue(10); // The value is a number: 10 printValue('hello'); // The value is a string: helloUsing
anydoesn't differ much from JavaScript code, so it's better to code utilizing TypeScript's advantages using union typesfunction printValue(value: number | string): void { if (typeof value === 'number') { console.log(`The value is a number: ${value}`); } else { console.log(`The value is a string: ${value}`); } } printValue(10); // The value is a number: 10 printValue('hello'); // The value is a string: helloThe above
printValuefunction receives number or string valuesAt this time, using union type to specify as
number | stringtypeThen check the type of input value using typeof operator → output different logs for number and string cases respectively
Like this, union types are useful when you need to handle values of various types
(1) Advantages of Union Type
Can infer types, so can easily get type-related APIs through autocomplete
Can improve code readability: explicitly shows that variables declared with types can have one value among string, number, boolean types, making code easier to understand
(2) Points to Note When Using Union Type
Need to be careful because you can only access members common to all types in the union
In the
askSomeonefunction, can only accessname, which is the common property thatDeveloperandPersonhave. Because only common and guaranteed properties should be providedIf you want to access other properties, you need to use type guards (Type guards: One of the features used to protect types in TypeScript, restricts type scope in specific code blocks to ensure type safety within that code block)
2. Intersection Type
Method of combining two or more types to create a new type
Expressed using
&operatorCombines types to receive all properties defined in
DeveloperandPersonrespectively belowCan express as a single type by connecting types with
&, so no type guards neededCan access all properties defined in the
askSomeonefunctionHowever, since it creates a new intersection of
DeveloperandPerson, when passing arguments, all properties must be sentConversely, union types need type guards but get choices when passing arguments
Last updated