問題のユニオンタイプに任意の種類のユーザー定義クラスが含まれている場合、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
を技術的には、ダックタイピングが本当にありませんが構造的タイピングと同じです。ダックタイピングは、使用されるメンバの存在のみを気にする実行時の現象であり、構造型は型のコンパイル時の比較です。 – Alex