我知道在TypeScript中有联合类型和交叉类型,但我找不到一种语法或解决办法来使用类型排除。是否有一种方法可以做到这一点?
type ValidIndices = string ^ '_reservedProperty'; // All strings but '_reservedProperty'
interface MyInterface {
[property: ValidIndices]: number;
_reservedProperty: any;
}
我知道在TypeScript中有联合类型和交叉类型,但我找不到一种语法或解决办法来使用类型排除。是否有一种方法可以做到这一点?
type ValidIndices = string ^ '_reservedProperty'; // All strings but '_reservedProperty'
interface MyInterface {
[property: ValidIndices]: number;
_reservedProperty: any;
}
这不是一个完整的答案。但如果你想为构造函数参数设置排除,你可以使用类似这样的代码:
declare type Params<T, K extends keyof T = never, D extends keyof T = never> = (
{[P in K]: T[P]} &
{[P in keyof T]?: T[P]} &
{[P in D]?: undefined }
)
...
class Control{
prop1: number
prop2: number
prop3: number
prop4: number
constructor(params: Params<Control, 'prop1' | 'prop2', 'prop4'>){
Object.assign(this, params)
...
"
params: {
prop1: number
prop2: number
prop3?: number
prop4?: undefined
}
type ValidIndices = "a" | "b" | "c" ...
然而,我认为你现在所寻找的功能并不存在于类型定义的一部分。
当然,你可以通过在MyInterface
的实现代码中来确保不使用非法值来实现这一点。但是你不能将其作为类型定义本身的一部分(除了字符串字面量,这可能不是你想要的)。