TypeScript for React Developer

More Types in TypeScript

Type Alias

Type alias is the naming of type, so you can reuse it.

ts
// instead of
const sanitize = (data: string | number) => {};
const clean = (data: string | number) => {};
// create a type alias to reuse
type StringOrNumber = string | number;
const sanit = (data: StringOrNumber) => {};
const clea = (data: StringOrNumber) => {};

Type alias is not limited to primitive, you can use it to name object type or function signature as well.

ts
type Job = {
name: string;
salary: number;
};
const a: Job = {
name: 'programmer',
salary: 0,
};
type Callback = () => void;
const hello: Callback = () => {
console.log('Hello!');
};
type NumberOrStringArray = Array<number | string>;
const items: NumberOrStringArray = [3, 'three', 4, 5];

Interface

Interface can be used to describe object and function. Interface cannot be used to describe primitive, such as string or boolean.

ts
interface Job {
name: string;
salary: number;
}
interface SuckyJob extends Job {
boring: true;
}

Most of the thing that you can do using interface can be done using type, so I usually just use type whenever possible.

Index signature

ts
type Person {
name: string;
age: number;
phone: string;
}
type PersonMap = {
[id: string]: Person;
}
const personMap: PersonMap = {
malcolm: {
name: 'Malcolm',
age: 29,
phone: '0139944857'
}
}
Comments

There is no comment on this post yet.

Issue on this page? Report here