0

Why does the code below compile fine when the variable id is declared as an number, when within the constructor it is being assigned a string?

interface IComplexType{
    id: number;
    name: string;
}

class ComplexType implements IComplexType{
    id: number;
    name: string;
    constructor(idArg: number, nameArg: string);
    constructor(idArg: string, nameArg: string);
    constructor(idArg: any, nameArg: any){
        this.id = idArg;
        this.name = nameArg;
    }

}

window.onload = () =>{
    var complexType: ComplexType = new ComplexType("hi","hi");
    console.log(complexType.id);

}

Thanks!

2 Answers 2

2

Short answer... because it isn't being assigned a string, it is being assigned a variable of type any.

this.id = idArg;

The any type means that the value "can be treated as any type". So when the compiler asks "can I assign any to a number" the answer is "yes".

You could narrow the type in the constructor (and eliminate the overloads, which is always a positive thing) with a union type:

class ComplexType implements IComplexType{
    id: number;
    name: string;
    constructor(idArg: string | number, nameArg: string){
        this.id = idArg;
        this.name = nameArg;
    }
}

This has the additional benefit of telling you that the assignment is a possible error, which would force you to update the signature (either to parse the number out of the string, or do whatever you intend when a string is supplied).

The key part of the example is string | number, which says the type is either a string or a number, which is more restrictive than any.

Sign up to request clarification or add additional context in comments.

Comments

2

Typescript compiles into JavaScript, that actually doesn't support function overloading. Overloaded declarations are used during compilation for type checking only.

This constructor

constructor(idArg: any, nameArg: any){
    this.id = idArg;
    this.name = nameArg;
}

allows to pass arguments of any type, so strings are allowed.

Inside the constructor passed values are assigned to the class properties. And there is no type casting occures during this operation - due to this is JavaScript.

You can find "Constructor overload in TypeScript" and find for example, this for more details and possible solutions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.