Skip to content

non-null assertion not working on IndexedAccess where K is a TypeParameter #21369

Closed
@ajafff

Description

@ajafff

TypeScript Version: 2.7.0-dev.20180123

Search Terms: indexed access, non null assertion, type parameter

Code

// --strictNullChecks enabled

interface I {
    foo?: string;
    bar?: string;
}

declare function take<T>(p: T): void;

function fails<K extends keyof I>(o: I, k: K) {
    take<string | undefined>(o[k]); // works
    take<string>(o[k]!); // Argument of type 'I[K]' is not assignable to parameter of type 'string'. Type 'string | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'.
}

// If the key is not generic, everything works as expected
function works<T extends I>(o: T, k: keyof I) {
    take<string>(o[k]!); // no error here, which should stay that way
}

Expected behavior:
No error as this worked very well in [email protected]

Actual behavior:
Error as stated in the inline comment.

Playground Link:

Related Issues:
Another recent change to IndexedAccess inference: #21368

Metadata

Metadata

Assignees

No one assigned

    Labels

    Breaking ChangeWould introduce errors in existing code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions