2017-04-10 126 views
0

考慮:打字稿類型限制分配

interface B { 
    base: string; 
} 
interface C1 extends B { 
    c1: string; 
} 
interface C2 extends B { 
    c2: string; 
} 

type A = C1 | C2; 

var aOk1: A = { 
    base: '', 
    c1: '', 
} 
var aOk2: A = { 
    base: '', 
    c2: '', 
} 
var a: A = { 
    base: '', 
    c1: '', // was expecting this to error at compile time 
    c2: '', // was expecting this to error at compile time 
} 

a.c1; // Correctly errors 
a.c2; // Correctly errors 

標示在代碼中,我期待雙方c1c2的分配屬性導致編譯時錯誤。有沒有辦法達到這個目的?

爲了澄清動機,這是因爲有設置一個選項的兩個相互排斥的方式反對,我希望把它在定義類型(.d.ts)文件中使用:

// definition in a .d.ts file 
someFunction(options: C1 | C2) 

使如果有人試圖通過不正確的選項設置,他們將被顯示在編譯時錯誤這兩個值對象,而是他們目前能做的,沒有任何編譯時錯誤如下:

// consuming in a .ts file 

// User might think both options will be used but 
// actually c2 option silently overrides c1. 
someFunction({base: '', c1: '', c2: ''}); 

** 編輯:標籤聯合類型 **

不能使用tagged union types又稱"Discriminated Unions"解決這個問題之一:

interface C1 extends B { 
    kind: 'C1', 
    c1: string; 
} 
interface C2 extends B { 
    kind: 'C2', 
    c2: string; 
} 

type A = C1 | C2; 

var a: A = { 
    kind: 'C1', 
    base: '', 
    c1: '', // would like this to compile time error 
    c2: '', // would like this to compile time error 
}; 
+0

你在尋找十字路口類型嗎? '類型A = C1 ' – Saravana

+0

嗨@Saravana,感謝您的評論。相交類型首先不會在'var a:A = {base:'',c1:'',c2:''}'中產生'c1'和'c2'錯誤(並且另外導致能夠訪問c1和C2沒有任何錯誤,這是絕對不正確的)。 – AJP

回答