Skip to content

Shouldn't allow a class instance passed to function if it is the wrong type #12811

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
eamodio opened this issue Dec 9, 2016 · 3 comments
Closed
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug

Comments

@eamodio
Copy link

eamodio commented Dec 9, 2016

TypeScript Version: 2.1.4

Code

Playground link

class Base {
    value: string;
    constructor(value: string) { this.value = value; }
}

class A extends Base {
    constructor(value: string) { super(value); }
}

class B extends Base {
    constructor(value: string) { super(value); }
}

function onlyA(o: A) { console.log("onlyA", o.value); }
function onlyB(o: B) { console.log("onlyB", o.value); }

let a = new A("a");
let b = new B("b");

onlyA(a); // good
onlyA(b); // bad
onlyB(b); // good
onlyB(a); // bad

Expected behavior:

I would expect the lines marked bad above to cause compile errors. I would expect this behavior when using interfaces, but not with classes.

Actual behavior:

Compiles without errors.

@zpdDG4gta8XKpMCd
Copy link

answer: https://github.com/Microsoft/TypeScript/wiki/FAQ#what-is-structural-typing

@RyanCavanaugh RyanCavanaugh added the Working as Intended The behavior described is the intended behavior; this is not a bug label Dec 9, 2016
@eamodio
Copy link
Author

eamodio commented Dec 9, 2016

OK, right that make sense. Although now that Class means something to javascript (a specific implementation) -- using structural typing when specifying a class seems "wrong". If I was using an interface, I totally agree.

But what actually sent me down this path was I originally tried this:

function onlyA(o: A) {
    if (o instanceof A) {
        console.log("onlyA - is A", o.value);
        return;    
    }
    console.log("onlyA - not A", o.value);
}

Playground link

But that doesn't compile, because it thinks o is the never type.

It feels like that is a bug right? @Aleksey-Bykov @RyanCavanaugh

@RyanCavanaugh
Copy link
Member

See #10422, #10648, #7271, etc

@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug
Projects
None yet
Development

No branches or pull requests

3 participants