How do I prevent TypeScript from allowing assigning similar but different types to a declared variable?
Consider following classes:
class Pe
So it works by design (you can't escape it). From the official documentation:
Classes work similarly to object literal types and interfaces with one exception: they have both a static and an instance type. When comparing two objects of a class type, only members of the instance are compared. Static members and constructors do not affect compatibility.
class Animal {
feet: number;
constructor(name: string, numFeet: number) { }
}
class Size {
feet: number;
constructor(numFeet: number) { }
}
var a: Animal;
var s: Size;
a = s; //OK
s = a; //OK
This is by design, TypeScript won't throw errors if the types match.
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".
http://www.typescriptlang.org/Handbook#interfaces
As a result, this is something that would be checked at runtime.
var arya: Woman = new Man();
if (arya instanceof Man) {
throw new Error("Dude looks like a lady! *guitar riff*");
}
TypeScript understands instanceof
so it can be used to cast types as well.
var jon: Man = new Woman();
if (jon instanceof Man) {
// The type of `jon` is Man
jon.getFullName();
}
if (jon instanceof Woman) {
// The type of `jon` is Woman
jon.getFullName();
}
Lastly you can also use type guards available in 1.6.
function isMan(a: Person): a is Man {
return a.getFullName().indexOf('Mr. ') !== -1;
}
var arya: Woman = new Man();
if(isMan(arya)) {
// The type of `arya` is Man
arya.getFullName();
}