TypeScript 小抄

奴止
Oct 20, 2022
Last edited: 2023-3-23
type
Post
status
Published
date
Oct 20, 2022
slug
typescript-cheatsheet
summary
一些常用的 TypeScript 小技巧,方便你我他。
tags
前端开发
TypeScript
category
技术随手记
icon
password
Property
Mar 23, 2023 03:48 AM
🔥
持续更新中….
 

基础知识点

 

类型推断、转换、断言等

 

类型推断

一般情况下会自动推断出类型,如:
const c1 = '123' // '123' let c2 = '123' // string
 
但有些时候,自动推断不太符合(或者说不够精确),需要加以干涉:
// 常量类型 let c3 = '123' as const // '123' const a1 = ['1', '2'] // string[] const a2 = ['1', '2'] as const // readonly ["1", "2"] const a3 = ['1', 2] // (string | number)[] const a4 = ['1', 2] as const // readonly ["1", 2]
 

函数返回的类型推断

使用关键词 is 来实现,根据参数推断,下方示例中的 isXX 的返回类型。
type X = { type: string val: string } type Y = { val: number } const isX = (x: X | Y) => { return 'type' in x } const mVar:X|Y = { val: 123 } if(isX(mVar)) { mVar.type // ERROR: Property 'type' does not exist on type 'Y' } const isXX = (x: X | Y): x is X => { return 'type' in x } if(isXX(mVar)) { mVar.type // ok }
 

类型强制转换

慎重使用不兼容的类型强转,或者说不要使用。
// 类型强转 let f1 = '123' let f2 = 123 f1 = f2 // error: 2322, Type 'number' is not assignable to type 'string' f1 = f2 as string // error: 2352 f1 = (f2 as unknown) as string // ok
 

强制不为空断言

慎重使用,除非你很确信此时一定不为空,否则还是交给静态类型来帮你把控。
// 通过 ! 指明 user.nickname 不为 null 或 undefined user.nickname!.split(' ')
 

常用工具类型

覆盖同名属性

 
/** * 用 R 替换 T 中同名属性 */ export type Replace<T, R> = Omit<T, keyof R> & R;
 

修改联合类型中某个类型的属性

假设有如下联合类型:
type A = { model: "001"; prop1: string[]; }; type B = { model: "002"; prop1: number; prop2: string; }; type C = { model: "003"; prop1: string; }; type ABC = A | B | C;
 
目标:修改 ABC 中的 A 中属性 prop1
const a1: ABC = { model: "001", prop1: ["12"] }; // 修改为 const a2: ABC1 = { model: "001", prop1: [{ content: "12", id: "111" }] };
 
方案:
/** * 用 M 来覆盖联合类型 U 的 T 中同名属性 */ type ModifyUnion<U, T, M> = U extends T ? Replace<U, M> : U; type ABC1 = ModifyUnion<ABC, A, { prop1: { content: string; id: string }[] }>;
 
 
TypeScript 常见问题github仓库添加在线页面