我需要创建一个排除某些文字类型并接受所有其他字符串的类型.我试过这个:
type ExcludedKeys = "a"|"b"
type MyType = {
[K in Exclude<string,ExcludedKeys>]: any
}
const obj: MyType = {
a: 0, // No Error
b: 1 // No Error
}
但很快我发现Exclude<string,ExcludedKeys>
只是string
,用这种方法是不可能的.然后,我try 了这种方法:
type ExcludedKeys = "a"|"b"
type MyType<T> = keyof T extends ExcludedKeys ? never : {
[K in keyof T]: T[K]
}
declare class Obj {
a: number
b: number
c: number // Adding this removes the wanted error.
}
const obj: MyType<Obj> = {
a: 0, // No Error
b: 1, // No Error
c: 3
}
但只有当ExcludedKeys
人的成员是该对象的唯一props 时,这才有效.
我需要的是
如上所述,否定可分配给一组字符串的属性名的类型
type ExcludedKeys = "a"|"b"
const obj = {
a: 0, // Error Here
b: 1, // Error Here
c: 3
}
编辑
尽管我没有提到它是为了简化上下文,但正如jsejcksn's answer指出的那样,我需要这个类型来保存给定类模型的类型信息.尽管如此,lepsch's answer仍然是被接受的,因为它以最短和最简单的方式完成了我所要求的事情.无论如何,我想分享我是如何改变这种方法以满足我的需求的.
type ExcludedKeys = "a"|"b"
type MyType<T> = {
[K in keyof T]: T[K]
} & {
[K in ExcludedKeys]?: never
}