Last active
May 9, 2023 06:02
-
-
Save junibrosas/3e3afa16251e030b906393a02e47aadb to your computer and use it in GitHub Desktop.
Advance Typescript CheatSheet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Advance Types | |
*/ | |
type ReadonlyProps<T> = { | |
readonly [P in keyof T]: T[P]; | |
} | |
interface Props { | |
title: string; | |
content: string; | |
} | |
type ReadonlyComponentProps = ReadonlyProps<Props>; | |
function ReadonlyPropsComponent(props: ReadonlyComponentProps) { | |
props.title = "New Title"; // Error: Cannot assign to 'title' because it is readonly property. | |
return ( | |
<div> | |
<h1>{ props.title } </h1> | |
<p>{ props.content } </p> | |
</div> | |
) | |
} | |
// ------------------------------------------------ | |
/** | |
* Discriminated Unions | |
*/ | |
type GoodShape = | |
| { kind: "circle"; radius: number } | |
| { kind: "rectangle"; width: number; height: number } | |
| { kind: "square"; size: number; } | |
function goodGetArea(shape: GoodShape): number { | |
switch (shape.kind) { | |
case "circle": | |
return Math.PI * shape.radius ** 2; | |
case "rectangle": | |
return shape.width * shape.height; | |
case "square": | |
return shape.size ** 2; | |
default: | |
const _exhaustiveCheck: never = shape; | |
return _exhaustiveCheck; | |
} | |
} | |
// ------------------------------------------------ | |
/** | |
* Type Guards | |
*/ | |
interface Person { | |
type: "person"; | |
name: string; | |
age: number; | |
} | |
interface Company { | |
type: "company"; | |
name: string; | |
numberOfEmployees: number; | |
} | |
type Entity = Person | Company; | |
function isPerson(entity: Entity): entity is Person { | |
return entity.type === 'person'; | |
} | |
function printEntityInformation(entity: Entity) { | |
if (isPerson(entity)) { | |
console.log(`Person ${entity.name} is ${entity.age} years old`); | |
} else { | |
console.log(`Company ${entity.name} has ${entity.numberOfEmployees} employees`); | |
} | |
} | |
/** | |
* Utility Types | |
*/ | |
// More | |
// https://www.typescriptlang.org/docs/handbook/utility-types.html | |
// Make a type nullable | |
type Nullable<T> = { [K in keyof T]: T[K] | null }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment