Lage.tech

BotmationNotes
moon indicating dark mode
sun indicating light mode

TypeScript - Advanced Types

Pick

Create a new type based on another type except refine its properties to the ones picked.

Applicable React example:

// User Model
interface User {
id: number,
first_name: string,
last_name: string,
phone: number,
address: string
}
// User component to display user's full name
const UserFullName = ({first_name, last_name}: Pick<User, 'first_name'|'last_name'>) => (
<h4>{ first_name } { last_name }</h4>
)

Record

Create a mapped type using values of an union type as keys and values type set to the subsequent generic.

Applicable React example:

type Statuses = "failed" | "complete";
interface Status {
iconType: IconTypes
iconColor: IconColors
}
const icons: Record<Statuses, Status> = {
failed: {
iconType: "warning",
iconColor: "red"
},
complete: {
iconType: "check",
iconColor: "green"
}
};
interface StatusProps {
status: Statuses
}
const Status = ({status}: StatusProps) => <Icon {...icons[status]} />