TS类型接口的一些操作

By赵的拇指At2019-11-28In4Views161

获取interface某一成员类型

interface IPeople {
  name: string;
  age: number;
  say: (words: string) => void;
}

现在需要获取成员say的类型

type say = IPeople['say']; // 使用方括号的形式即可获取say类型,不能使用IPeople.say来获取

排除interface某一成员

interface IPeople {
  name: string;
  age: number;
  say: (words: string) => void;
}

现在需要获取成员say的类型

type newPeople1 = Omit<IPeople, 'say'>; // 排除say成员
type newPeople2 = Omit<Omit<IPeople, 'say'>, 'name'> // 排除say,name

将类型所有成员变成可选

interface IPeople {
  name: string;
  age: number;
  say: (words: string) => void;
}
type IPeopleBad = Partial<IPeople>;

将类型所有成员变成只读

interface IPeople {
  name: string;
  age: number;
  say: (words: string) => void;
}
type IPeopleBad = Readonly<IPeople>;