2017-04-10 131 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

回答