Skip to content

Pick non-null member of nullable mapped type #15643

Closed
@NN---

Description

@NN---

I have a simple code which checks property for null and throws exception if it is null or returns the value.

function getNonNull<T extends object, K extends keyof T>(obj: T, key: K): T[K] {
  const v = obj[key]; 
  if (v != null) {
    return v;
  } else {
    throw "A";
  }
} 

The only catch that it doesn't say it returns non-null value.

const a = getNonNull({a:null},"a"); // a : null

I am trying to improve function to set 'obj' as an object of type [K in string]: U | null | undefined and then TypeScript would return 'U'.

Unfortunately TypeScript doesn't like it and types 'U' as '{}' instead of correct type.

function getNonNull<
  U,
  T extends {[K in string]: U | null | undefined },
  K extends keyof T
  >(obj: T, key: K): T[K] {
  
  const v = obj[key]; 
  if (v != null) {
// error TS2322: Type 'T[K]' is not assignable to type 'U'.
//  Type 'U | null | undefined' is not assignable to type 'U'.
//    Type 'undefined' is not assignable to type 'U'.
    return v; 
  } else {
    throw "A";
  }
} 

Do I miss something ?

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions