Published on

类型操作

Authors
  • avatar
    Name
    李丹秋
    Twitter

泛型

Generic Type

function identity<Type>(arg: Type): Type {
  return arg;
}
 
let myIdentity: <Type>(arg: Type) => Type = identity;

泛型限制

使用extends关键字

interface Lengthwise {
  length: number;
}
 
function loggingIdentity<Type extends Lengthwise>(arg: Type): Type {
  console.log(arg.length); // Now we know it has a .length property, so no more error
  return arg;
}

使用keyof

function getProperty<Type, Key extends keyof Type>(obj: Type, key: Key) {
  return obj[key];
}
 
let x = { a: 1, b: 2, c: 3, d: 4 };
 
getProperty(x, "a");
getProperty(x, "m");
Argument of type '"m"' is not assignable to parameter of type '"a" | "b" | "c" | "d"'.

keyof

keyof操作符可以提取对象的所有key,然后生成一个联合类型

type Point = { x: number; y: number };
type P = keyof Point;
// type P = “x” || "y"

Indexed Access Types

type I1 = Person["age" | "name"];
     
type I1 = string | number
 
type I2 = Person[keyof Person];
     
type I2 = string | number | boolean
 
type AliveOrName = "alive" | "name";
type I3 = Person[AliveOrName];

实现一个Pick

type MyPick<T, K extends keyof T> = {
  [key in K]: T[key]
}

extends 操作符

  1. 在JS中,担当类的继承重担,例如 App extends Component
  2. 在TS中,当泛型约束,例如 type ToUpper<S extends string> = xxx
  3. 在TS类型中,条件判断的关键词 type ReturnType<T> = T extends string ? string : number

infer关键字

infer 表示在 extends 条件语句中待推断的类型变量。

type ParamType<T> = T extends (arg: infer P) => any ? P : T;

在这个条件语句 T extends (arg: infer P) => any ? P : T 中,infer P 表示待推断的函数参数。整句表示为:如果 T 能赋值给 (arg: infer P) => any,则结果是 (arg: infer P) => any 类型中的参数 P,否则返回为 T。

TS类型遍历

// js 对象遍历
const person = {
    name: '张三',
    age: 18,
    id: 1,
}

for (const key in person) {
    console.log(key, person[key]);
}

// ts 类型对象遍历
type Person = {
    name: string;
    age?: number;
    readonly id: number;
}

type Readonly<T> = {
    readonly [Key in keyof T]: T[Key];
}

keyof 关键字可以获取到对象所有的属性

Key 就是每次遍历时存的属性名

T[Key] 就是每次遍历时存的属性值

(typescript学习:关键字,操作符,keyof,in,infer...)[https://blog.csdn.net/weixin_44828005/article/details/120953059]