xxxxxxxxxx
let myVar : string | number; //myVar can store string and number types
xxxxxxxxxx
/*
TypeScript allows us to use more than one data type for a variable
or a function parameter. This is called union type.
*/
let code: (string | number);
code = 123; // OK
code = "ABC"; // OK
code = false; // Compiler Error
let empId: string | number;
empId = 111; // OK
empId = "E111"; // OK
empId = true; // Compiler Error
xxxxxxxxxx
type Cow = {
name: string;
moo: () => void;
};
type Dog = {
name: string;
bark: () => void;
};
type Cat = {
name: string;
meow: () => void;
};
// union type
type Animals = Cow | Dog | Cat;
xxxxxxxxxx
let myVar : string | number; //Variable with union type declaration
myVar = 100; //OK
myVar = 'Lokesh'; //OK
myVar = true; //Error - boolean not allowed
xxxxxxxxxx
function numOrString(inp: string | number) {
console.log(inp);
}
/*this means can be eiter a string or a number*/
xxxxxxxxxx
// Union Type: function reacts depending on x type (array of string OR string)
function welcomePeople(x: string[] | string) {
if (Array.isArray(x)) {
console.log("Hello, " + x.join(" and ")); // 'x' is 'string[]'
} else {
console.log("Welcome lone traveler " + x); // 'x' is 'string'
}
}
xxxxxxxxxx
type Circle = { kind: 'circle'; radius: number };
type Rect = { kind: 'rect'; width: number; height: number };
type Shape = Circle | Rect;
function getArea(shape: Shape) {
return shape.kind === 'circle' ?
Math.PI * shape.radius ** 2
: shape.width * shape.height;
}
xxxxxxxxxx
// Example of using union types in TypeScript
// Union type allows a variable to have multiple types
let myVariable: string | number;
myVariable = "Hello"; // Assigning a string value
console.log(myVariable.length); // Output: 5
myVariable = 10; // Assigning a number value
console.log(myVariable.toFixed(2)); // Output: 10.00
// Union types can also be used with function parameters
function printValue(value: string | number) {
console.log(value);
}
printValue("Hello from union type!"); // Output: Hello from union type!
printValue(20); // Output: 20