本文阅读量 次
1. TypeScript¶
1.1 TS 中一些类型定义的高级用法¶
用法 | 说明 | 备注 |
---|---|---|
Awaited<Type> | ||
Partial<Type> | 基于 Type, 所有属性均变为可选的 | |
Required<Type> | 基于 Type, 所有属性均变为必选的 | |
Readonly<Type> | 基于 Type, 所有属性均变为只读的 | |
Record<Keys, Type> | ||
Pick<Type, Keys> | 基于 Type,选取 Type 中的 Keys 作为新类型的成员 | |
Omit<Type, Keys> | 基于 Type,但忽略 Keys | 相反操作是 Pick |
Exclude<UnionType, ExcludedMembers> | ||
Extract<Type, Union> | ||
NonNullable<Type> | ||
Parameters<Type> | ||
ConstructorParameters<Type> | ||
ReturnType<Type> | ||
InstanceType<Type> | ||
NoInfer<Type> | ||
ThisParameterType<Type> | ||
OmitThisParameter<Type> | ||
ThisType<Type> | ||
Uppercase<StringType> | ||
Lowercase<StringType> | ||
Capitalize<StringType> | ||
Uncapitalize<StringType> |
1.2 TS 中的 Type 和 Class 的区别¶
- https://www.typescriptsos.com/basics/what-is-the-difference-between-type-and-class-in-typescript/ ⧉
- https://www.jianshu.com/p/7de23726c14e ⧉
1.3 Interface 和 Type 的区别¶
- Interface 可以进行声明合并(Declaration Merging,多个地方声明同一个目标),但 Type 不支持
interface Window {
title: string;
}
interface Window {
ts: TypeScriptAPI;
}
const src = 'const a = "Hello World"';
window.ts.transpileModule(src, {});
type Window = {
title: string;
}
type Window = {
ts: TypeScriptAPI;
}
// Error: Duplicate identifier 'Window'.
1.4 HowTo¶
1.4.1 如何进行两个对象之间的转换¶
https://www.typescriptsos.com/advanced/map-an-object-to-another-in-typescript/ ⧉
方法1: Object.assign()
const sourceObject = { name: 'John', age: 25 };
const targetObject = Object.assign({}, sourceObject);
console.log(targetObject); // Output: { name: 'John', age: 25 }
方法2: 使用 Spread Operator
操作符
const sourceObject = { name: 'John', age: 25 };
const targetObject = { ...sourceObject };
console.log(targetObject); // Output: { name: 'John', age: 25 }
方法3: 使用 mapping 函数
本质上是定义了一个转换函数,可以支持源字段名和目的字段名不一样的场景
interface SourceObject {
name: string;
age: number;
}
interface TargetObject {
fullName: string;
yearsOld: number;
}
const sourceObject: SourceObject = { name: 'John', age: 25 };
const mapObject = (source: SourceObject): TargetObject => {
return {
fullName: source.name,
yearsOld: source.age
};
};
const targetObject: TargetObject = mapObject(sourceObject);
console.log(targetObject); // Output: { fullName: 'John', yearsOld: 25 }