Skip to content

Narrowing mapped types to exclude undefined values #13528

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

Closed
jg opened this issue Jan 17, 2017 · 2 comments
Closed

Narrowing mapped types to exclude undefined values #13528

jg opened this issue Jan 17, 2017 · 2 comments

Comments

@jg
Copy link

jg commented Jan 17, 2017

Problem

TypeScript Version: 2.1.4

Code

(--strictNullChecks)

interface Store {
  value: string | undefined
}

export function get<K extends keyof Store>(
  store: Store,
  fieldName: K
): Store[K] {
  if (store[fieldName] == undefined) throw(fieldName + " is undefined!");

  return store[fieldName]
}

const store: Store = { value: "stuff" }

const result = get(store, "value").replace("stuff", "otherstuff")

Expected behavior:

(It's possible to narrow the resulting type of get to exclude undefined values)

Actual behavior:

Type error is reported: get(a, "value") is possibly undefined.

Proposal

I'd propose an operator which could be used to express that the mapped type does not contain undefined. Consider the use of bang (!) operator below:

export function get<K extends keyof Store>(
  store: Store,
  fieldName: K
): Store[K]! {
  if (store[fieldName] == undefined) throw(fieldName + " is undefined!");

  return store[fieldName]
}
@aluanhaddad
Copy link
Contributor

I believe this is what you are looking for #12578

@jg
Copy link
Author

jg commented Jan 17, 2017

Yep

@jg jg closed this as completed Jan 17, 2017
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants