From c514341b291bf0e7851ecef89e9d12bcee345995 Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Mon, 28 Nov 2022 10:47:57 -0500 Subject: [PATCH] doc: update typescript.md (#186) --- docs/typescript.md | 78 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) diff --git a/docs/typescript.md b/docs/typescript.md index 20eeed09..6759b2ba 100644 --- a/docs/typescript.md +++ b/docs/typescript.md @@ -1325,6 +1325,84 @@ const point = [3, 4] as const // type 'readonly [3, 4]' ``` +### satisfies + +`satisfies` 允许将验证表达式的类型与某种类型匹配,而无需更改该表达式的结果类型。 + +```ts +type Colors = 'red' | 'green' | 'blue'; + +type RGB = [red: number, green: number, blue: number]; + +const palette: Record = { + red: [255, 0, 0], + green: '#00ff00', + blue: [0, 0, 255], +}; + +// 通常的方式会推导出 redComponent 为 string | number | undefined +const redComponent = palette.red.at(0); +``` + +#### 使用 satisfies + +```ts +const palette = { + red: [255, 0, 0], + green: '#00ff00', + blue: [0, 0, 255], +} satisfies Record + +// undefined | number +const redComponent = palette.red.at(0) +``` + + + +### 范型实例化表达式 + +不使用的情况下: + +```ts +const errorMap: Map = new Map() +// 或者使用 type 定义别名 +type ErrorMapType = Map +``` + +使用泛型实例化表达式: + +```ts +const ErrorMap = Map +const errorMap = new ErrorMap() +``` + +#### 泛型实例化函数 + +```ts +function makeBox(value: T) { + return { value }; +} +``` + +--- + +不使用: + +```ts +function makeHammerBox(hammer: Hammer) { + return makeBox(hammer); +} +// or... +const makeWrenchBox: (wrench: Wrench) => Box = makeBox; +``` + +使用: + +```ts +const makeStringBox = makeBox; +makeStringBox(42); +``` + CLI ---