Skip to content

in 2.1.4, strictNullChecks make index types of nullable fields be never  #12747

Closed
@scottbessler

Description

@scottbessler

TypeScript Version: 2.1.4

Code

function get<T, K extends keyof T, K2 extends keyof T[K]>(obj: T, propertyName: K, propertyName2: K2): T[K][K2] | undefined {
    const step1 = obj ? obj[propertyName] : undefined;
    return step1 ? step1[propertyName2] : undefined;
}

interface Org {
    admin?: User;
}
interface User {
    email?: string;
}

const o: Org = { admin: { email: 'foo' } };
const o2: Org = {};

console.log(get(o, 'admin', 'email'))
console.log(get(o2, 'admin', 'email'))

Expected behavior:

Expect to output:

foo
undefined

Actual behavior:
with strictNullChecks, fails to compile:

foo.ts(17,29): error TS2345: Argument of type '"email"' is not assignable to parameter of type 'never'.
foo.ts(18,30): error TS2345: Argument of type '"email"' is not assignable to parameter of type 'never'.

works without strictNullChecks:

foo
undefined

Metadata

Metadata

Assignees

No one assigned

    Labels

    In DiscussionNot yet reached consensusSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions