Skip to content
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

typecasting to a generic interface from an object literal #13931

Closed
sramam opened this issue Feb 7, 2017 · 2 comments
Closed

typecasting to a generic interface from an object literal #13931

sramam opened this issue Feb 7, 2017 · 2 comments
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug

Comments

@sramam
Copy link

sramam commented Feb 7, 2017

TypeScript Version: 2.1.5

interface Orig<T extends string> {
    type: T;
}

type TypeId = 'SpecA';

interface SpecA extends Orig<TypeId> {
    name?: string;
}

const goodCast = <SpecA>{
    type: 'SpecA'
}

const badCast = <SpecA>{
    type: 'SpecB'
}
// throws an error:
// Type '{ type: "SpecB"; }' cannot be converted to type 'SpecA'.
//  Types of property 'type' are incompatible.
//    Type '"SpecB"' is not comparable to type '"SpecA"'.

const justData = {
    type: 'SpecB'
};

const castLater = <SpecA>justData;
// Expected an error to be thrown, but the compiler accepts this.

Expected behavior:
The typecast to castLater should trigger a compile error.

Actual behavior:
it doesn't.

@RyanCavanaugh RyanCavanaugh added the Working as Intended The behavior described is the intended behavior; this is not a bug label Feb 7, 2017
@RyanCavanaugh
Copy link
Member

RyanCavanaugh commented Feb 7, 2017

justData gets type { type: string } so the downcast to { type: 'SpecA' } is OK. It gets that type (rather than { type: 'SpecB' }) so that it's not illegal to write e.g. `justData.type = 'whatever'". This logic doesn't apply in the earlier cases because a "fresh" object literal is known to not be mutated (or need to be able to be mutated) between when it's created and when it's bound to the variable it's initializing.

@sramam
Copy link
Author

sramam commented Feb 7, 2017

aah. makes sense.

castLater does get the cast:

castLater.type = 'SpecA'; is ok (as desired)
castLater.type = 'SpecB'; isn't
Even
castLater.type = justData.type; triggers an error.

That was the purpose of the cast in the first place.

Thanks for the clarification.

@sramam sramam closed this as completed Feb 7, 2017
@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

2 participants