TypeScript 中的对象类型不是一个常见的混淆来源exact(按照要求女士/TS#12936 https://github.com/Microsoft/TypeScript/issues/12936)。类型的值Student
is known具有name
, surname
, age
, and email
适当类型的属性,但不知道有only这些属性。这可以让您extend https://www.typescriptlang.org/docs/handbook/2/objects.html#extending-types通过向其添加已知属性来类型:
interface Student {
name: string,
surname: string,
age: number,
email: string
}
interface HogwartsStudent extends Student {
house: string,
spells: string[]
}
上式中,一个HogwartsStudent
是一种特殊类型Student
。如果我给你一个Student
,你不知道她是not a HogwartsStudent
,所以你不能确定她没有house
or spells
财产。
The Omit<T, K>
类型别名产生一个超类型 of T
。那是,T
延伸Omit<T, K>
。每个类型的值T
也是一个类型的值Omit<T, K>
。你所“省略”的一切Omit<T, K>
是已知的属性存在和类型,其中的键为K
.
您要求的不仅是从类型中删除已知的键,而且是从生成的对象中删除实际属性。这需要在运行时发生,就像在 JavaScript 中执行的方式一样:
function omit_student<K extends Array<keyof Student>>(
student: Student, ...props: K): Omit<Student, K[number]> {
const newStudent: Omit<Student, K[number]> = Object.assign({}, student);
for (let prop of props) {
delete (newStudent as any)[prop];
}
return newStudent;
}
请注意,我使用了剩余元组类型 https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html#tuples-in-rest-parameters-and-spread-expressions为了K
参数,但你也可以按照你的方式来做。