2016-10-13 3 views
0

問題のユニオンタイプに任意の種類のユーザー定義クラスが含まれている場合、typescript 2.0.3コンパイラが無効な割り当てなしでコンパイルされます。Typescript Union Typeは、カスタムクラスがユニオンに含まれていれば識別を停止します

例:

class Bar {} 

// Complains as expected: 
interface Foo { 
    bar: number|string 
} 

// Does not complain, surprisingly: 
interface Foo2 { 
    bar: number|string|Bar 
} 

var a = <Foo> { 
    bar: 5 
}; 
var a2 = <Foo> { 
    bar: "yar" 
}; 
//var a3 = <Foo> { 
// bar: new Date() // compiler complains as expected. 
//}; 

var b = <Foo2> { 
    bar: new Date() // compiler does not complain, I am confused. 
}; 

私はa3のコメントを外したときに私が得るコンパイラエラーがある:私はbを割り当てるときに、同じエラーが表示されることを期待する

lib/src/thing.ts(18,10): error TS2352: Type '{ bar: Date; }' cannot be converted to type 'Foo'. 
    Types of property 'bar' are incompatible. 
    Type 'Date' is not comparable to type 'string | number'. 
     Type 'Date' is not comparable to type 'number'. 

が、それは文句なしでうまくコンパイル。

これは既知の問題ですか?または、これが期待される動作で、なぜこれを有効とみなすべきか見ていませんか?私は自分自身で定義したクラスを含むいくつかのプロパティの1つであることを保証するために、ユニオンタイプに頼ることができたいと考えています。

ありがとうございました!


編集:私は少しより多くのテストを行なったし、さらに簡単な例を思い付いた:あなたのBarクラスので

One of TypeScript’s core principles is that type-checking focuses on the shape that values have. This is sometimes called “duck typing” or “structural subtyping”

written in the docsとして、

class Bar {} 

var a = <string|number> 4; 
var b = <string|number> "thing"; 
var c = <string|number> new Bar(); // works: confusing 
var d = <Bar> 4;     // ... confusing 
var f = <number> new Bar();  // ... also confusing 

答えて

1

活字体がduck typingを使用していますが空の場合、コンパイラはDateオブジェクトをBarと一致させるように管理します。これは矛盾がないためですs。
しかし、あなたは、あなたがエラーを取得しますBarにメンバーやメソッドを追加すると:

class Bar { 
    x: number; 
} 

var b = <Foo2> { 
    bar: new Date() 
}; 

が生成されます

Type '{ bar: Date; }' cannot be converted to type 'Foo2'. 
    Types of property 'bar' are incompatible. 
    Type 'Date' is not comparable to type 'string | number | Bar'. 
     Type 'Date' is not comparable to type 'Bar'. 
     Property 'x' is missing in type 'Date'. 

code in playground

+0

を技術的には、ダックタイピングが本当にありませんが構造的タイピングと同じです。ダックタイピングは、使用されるメンバの存在のみを気にする実行時の現象であり、構造型は型のコンパイル時の比較です。 – Alex

関連する問題