2017-05-24 37 views
4

我知道類型聯盟在類型的腳本&型路口,但我無法找到一個語法或解決方法使用類型排除。有沒有辦法做到這一點?打字稿排除?

type ValidIndices = string^'_reservedProperty'; // All strings but '_reservedProperty' 
interface MyInterface { 
    [property: ValidIndices]: number; 
    _reservedProperty: any; 
} 
+0

有[建議](https://github.com/Microsoft/TypeScript/issues/4183)的減法類型 –

回答

0

如果有一組有限的字符串值是允許的,那麼你可以使用字符串字面量的類型

type ValidIndices = "a" | "b" | "c" ... 

不過來定義他們,我不認爲該功能,您正在尋找現在作爲類型定義的一部分。

你當然也可以通過在你的實現MyInterface代碼實現這一目標,以確保非法值不被使用。但是你不能把它作爲類型定義本身的一部分(除了你可能不想要的字符串文字外)。

0

它不是一個完全回答。但是,如果你想設置爲排除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 
}