2

If i have:

var greeter: Greeter = new Sausage();

And both the Greeter class and Sausage class have the same functions and properties in them, the variable greeter will quite happily be filled up with a Sausage... How can i stop this?

For example, the following code compiles fine :(

class Greeter {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}

class Sausage {
    size: number;
    name: string;
    greeting: string;

    constructor() {
        this.size = this.SausageLogic(); 
    }

    private SausageLogic(): number {
        return this.size * 3;
    }
    greet() {
        return "Hello, ";
    }
}

var greeter: Greeter = new Sausage();

1 Answer 1

5

TypeScript uses a structural type system. Even though you didn't say Sausage extends Greeter, Sausage is still a subtype of Greeter because it has at least all the same members that Greeter does. Notice that anything you can do with a Greeter (access its greeting property or invoke its greet method) is legal to do with a Sausage.

If you were to add a method foo to Greeter, or remove the greeting property from Sausage, for example, that last line of code would become an error. Any private member is also enough to cause a structural mismatch (unless Sausage was explicitly derived from Greeter).

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

5 Comments

What is the benefit of this loose type structural nonsense... Or is it a compromise because of JavaScript's failings?
Is there any built in way to keep this type check from failing compilation... I see many situations where this could cause issues... Other than manually adding a unique id as a property to each class thus showing error. If not... Is there another language I can use that does check this type and show errors? Is the typescript compiler open source so I can change it?
@Jimmyt1988 yes to your last question (see github.com/Microsoft/TypeScript/issues/274)
@xmojmr - Mega helpful, I hope it comes into fruition

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.