我知道类型联盟在类型的脚本&型路口,但我无法找到一个语法或解决方法使用类型排除。有没有办法做到这一点?打字稿排除?
type ValidIndices = string^'_reservedProperty'; // All strings but '_reservedProperty'
interface MyInterface {
[property: ValidIndices]: number;
_reservedProperty: any;
}
我知道类型联盟在类型的脚本&型路口,但我无法找到一个语法或解决方法使用类型排除。有没有办法做到这一点?打字稿排除?
type ValidIndices = string^'_reservedProperty'; // All strings but '_reservedProperty'
interface MyInterface {
[property: ValidIndices]: number;
_reservedProperty: any;
}
如果有一组有限的字符串值是允许的,那么你可以使用字符串字面量的类型
type ValidIndices = "a" | "b" | "c" ...
不过来定义他们,我不认为该功能,您正在寻找现在作为类型定义的一部分。
你当然也可以通过在你的实现MyInterface
代码实现这一目标,以确保非法值不被使用。但是你不能把它作为类型定义本身的一部分(除了你可能不想要的字符串文字外)。
它不是一个完全回答。但是,如果你想设置为排除PARAMS contsructor你可以使用这样的代码:
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
}
有[建议](https://github.com/Microsoft/TypeScript/issues/4183)的减法类型 –