join two types in typescript

You can join two types in TypeScript using the Union (|) operator. The resulting type will be a type that can hold values of either of the two input types.

Here’s an example:

index.ts
type MyType = string | number;
31 chars
2 lines

In this example, MyType is a union type that can hold both strings and numbers.

You can also use Type Aliases to join types:

index.ts
type StringOrNumber = string | number;
39 chars
2 lines

In this example, StringOrNumber is a Type Alias for the union type string | number.

You can then use this type alias throughout your code:

index.ts
function printValue(value: StringOrNumber) {
  console.log(value);
}

printValue("Hello!"); // logs "Hello!"
printValue(123); // logs 123
138 chars
7 lines

gistlibby LogSnag