Skip to content

Problem with inference for this['prop'] with conditional types #27014

Open
@dfreeman

Description

@dfreeman

TypeScript Version: typescript@3.1.0-dev.20180907
Search Terms: this type, conditional type

Code

type Wrapped<T> = { ___secret: T };
type Unwrap<T> = T extends Wrapped<infer U> ? U : T;

declare function set<T, K extends keyof T>(obj: T, key: K, value: Unwrap<T[K]>);

class Foo {
    prop: Wrapped<string>;

    method() {
        set(this, 'prop', 'hi'); // <-- type error
    }
}

set(new Foo(), 'prop', 'hi'); // <-- typechecks

Expected behavior:
Both calls to set (the one in the method with this and the external one with new Foo()) pass typechecking.

Actual behavior:
The external call passes, but the one inside method fails with Argument of type '"hi"' is not assignable to parameter of type 'Unwrap<this["prop"]>'..

If I explicitly annotate this: Foo in the method signature or set the type parameters set<Foo, 'prop'>(...), everything passes.

We've run into this in the Ember type declarations, and have had to weaken the types for the time being to work around it.

Playground Link: available here

Related Issues: I wasn't able to find anything that seemed related to this issue.

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptDomain: Conditional TypesThe issue relates to conditional types

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions