1

I've just started learning TypeScript and I'm having a hard time wrapping my head around an interface behavior from the beginning tutorial on http://www.typescriptlang.org/Playground/#tut=ex5

As I understand it, the interface should enforce the type of the parameters, however this particular line throws me off

var user = new Student("Jane", "M.", "User");

It compiles correctly and all is well, but when I modify it to

var user = new Student(1, 2, 3);

it also compiles just fine.

Could anyone elaborate why it's working ?

I understand that this is a beginners question but I could not find any info on this searching online and I don't have any TypeScript experts around me.

Thanks in advance, Eugene

1 Answer 1

1

The type of the Student constructor parameters is any because there is no type annotation:

class Student {
    fullname : string;
    constructor(public firstname, public middleinitial, public lastname) {
        this.fullname = firstname + " " + middleinitial + " " + lastname;
    }
}

If we change it to have some type annotations, we'll get an error:

class Student {
    fullname : string;
    constructor(public firstname: string, // <-- add ': string' here
                public middleinitial: string, // and here
                public lastname: string) { // and here
        this.fullname = firstname + " " + middleinitial + " " + lastname;
    }
}

var x = new Student(1, 2, 3); // Error
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for you response, Ryan! It does make me wonder however that if interface can't enforce the data type, what's the point of specifying it in the interface?

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.