Typescript小知识

1 Utility Types(工具类型)

keyof

只抽属性名

interface exampleA {
  name:string;
  id:number;
  create:string;
}

type TypeA = keyof exampleA; // 其实就相当于 type TypeA = 'name'|'id'|'create'
let b:TypeA = 'name';
b = 'id';
// b = 'end'; // Type '"end"' is not assignable to type 'keyof exampleA'
console.log(b)

Partial<T>

所有属性都改成optional

与这个操作相反的是Required<T>

interface A {
  name:string;
  id:string
}

let a: Partial<A> = {
  name:'tangjie'
}
console.log(a)

Pick<Type, Keys>

选一些属性

interface A {
  id: string;
  name: string;
  age: number;
}
type B = Pick<A, "name" | "age">;

const xiaoming: B = {
  name: "xiaoming",
  age: 26,
};

Omit<Type, Keys>

移除属性

interface A {
  id: string;
  name: string;
  age: number;
}

const a:Omit<A,'id'> = {
  name:'tangjie',
  age:18,
  // id:1 如果加了这个属性就报错
}

Parameters<Type>

提取函数的参数

declare function f1(arg: { a: number; b: string }): void;
type A = Parameters<() => string>;// 相当于A = []    
type B = Parameters<(s: string) => void>;// 相当于 B = [s: string]

参考:https://juejin.cn/post/6971993738469965837

官方完整版:https://www.typescriptlang.org/docs/handbook/utility-types.html

Leave a Reply

Your email address will not be published. Required fields are marked *