【发布时间】:2021-07-06 11:13:24
【问题描述】:
我正在为学校做一个简单的项目。我想知道是否可以在 TypeScript 中省略某些类型的所有属性。
type Student = {
firstName: string
lastName: string
age: number
gender: Gender
courses: List<Course>
}
所以在这种情况下,我只想要一个包含 Student 的所有内容的类型,而没有 "courses"。
是否可以生成一个类型,它是 Student,但没有具有 List 类型的所有属性?它需要是通用的,因此它适用于所有类型,例如:
type Program = {
name: string
errors: List<Error>
successes: List<Success>
warnings: List<Warning>
}
现在它会给出一个只包含 { name: string }
的类型如果可能的话,有谁知道如何做到这一点?也许有条件类型?如果列表省略?
非常感谢所有帮助!
更新:添加代码示例:
type WithoutList<T> = {
[K in keyof T]: T[K] extends List<any> ? never : T[K]
}
const select = <a, b extends keyof WithoutList<a>>(arg: a, ...keys: b[]) => {
return null!
}
const s1: Student = {
firstName: 's',
lastName: 's',
age: 22,
gender: 'female',
courses: List<Course>(),
}
select(s1, 'courses') // courses should not be available here!
【问题讨论】:
-
type OmitLists<T> = { [P in keyof T]: T[P] extends List<any> ? never : T[P] };
标签: typescript types typescript-typings typescript-generics