How to prevent assiging similar types?

前端 未结 2 1639
天命终不由人
天命终不由人 2020-12-21 15:20

How do I prevent TypeScript from allowing assigning similar but different types to a declared variable?

Consider following classes:

class Pe         


        
2条回答
  •  别那么骄傲
    2020-12-21 16:05

    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
    

提交回复
热议问题