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

Pick non-null member of nullable mapped type #15643

Closed
NN--- opened this issue May 7, 2017 · 2 comments
Closed

Pick non-null member of nullable mapped type #15643

NN--- opened this issue May 7, 2017 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@NN---
Copy link

NN--- commented May 7, 2017

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 ?

@mhegazy
Copy link
Contributor

mhegazy commented May 8, 2017

looks like the same issue as #14366.

@mhegazy mhegazy added the Duplicate An existing issue was already created label May 8, 2017
@mhegazy
Copy link
Contributor

mhegazy commented May 22, 2017

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

2 participants