Cats Coffee Code
Published in

Cats Coffee Code

Tip of the Day — Typescript dynamic types

In Typescript, we can make our types dynamic with union types, intersection types, and index signatures.

union types

A union type allows us to define a variable with multiple types.

let myVar: number | string;

intersection types

An intersection type combines multiple types into one.

interface IEmployee {
id: string;
age: number;
name: string;
}
interface IContractEmployee {
termDuration: string;
}
type A = IEmployee & IContractEmployee;let x: A;x.age = 5;
x.id = 'CID5241';
x.termDuration = 'one week';

index signatures

In javascripy we can access to a member of an object by key. This is where we use index signature types.

type RestrictedStyleAttribute = "color" | "background-color" | "font-weight";type IRestrictedStyle = {
[T in RestrictedStyleAttribute]: string;
}

--

--

--

A magazine for typical web developers/engineers, who love cats, drink coffee and write code.

Recommended from Medium

Beyond the Framework, using React-Native with Swift and Kotlin

iOS Guide to TurboModules in React-Native for Early Adopters

【DTM】Visual Event Tracking for Web Pages (Three)

The Error Boundary Gotcha

Error: [Error: ORA-12560: TNS:protocol adapter error] {  errorNum: 12560,  offset: 0  }

await in useEffect()

Javascript Array Method .find()

Immutability in JavaScript

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Homa

Homa

Student of life

More from Medium

Summary of high-level built-in types in TypeScript

typescript

Invariant-style assertion functions in TypeScript

Publish Typescript Package in NPM

TypeScript language