2

Given a type T:

type T = {
  akey: string | number | undefined
}

If I check specifically for it

const fun = (p: T) => {
  if(!p.akey) return
  p.akey.toString()
}

Typescript understands that akey can't be undefined.

If I do it generically though:

const fun2 = (p: T) => {
  if(Object.values(p).includes(undefined)) return
  p.akey.toString()
}

It does not: Object is possibly 'undefined'.

How can I make typescript understand so I don't have to do:

p.akey!.toString()

Trufa
  • 39,971
  • 43
  • 126
  • 190
  • What you call doing it generically doesn't actually check the key, hence typescript not knowing whether it's defined or not. Perhaps you could use Partial and then after the check mark `p` as MyType? – Webber May 24 '22 at 12:43
  • @Webber What do you mean? The key `akey` itself will never be undefined cause it's required by `T` or am I missing something? – Trufa May 24 '22 at 12:47
  • Exactly. Since you're doing `.includes()` I assume that any of the keys might be missing. If so, you can use `Partial` where `interface MyType { akey: string | number }` or `interface MyType { [key: string]: string | number }`. – Webber May 24 '22 at 12:50
  • I've deleted my answer in favour of https://stackoverflow.com/a/43895205/3593896 – Webber May 24 '22 at 14:00
  • Does [this](https://tsplay.dev/mp9b7W) work for you? If so, I can write up an answer detailing why it works and how I came up with it. If not, what am I missing? – kelsny May 24 '22 at 18:41
  • @catgirlkelly thanks again for taking the time! Two question on a row you're solving me, I mean, it does what it's supposed to so I guess it answers my question, I do feel like it's an overkill, for now when I'm iterating which I need to do anything I'm checking in the loop the value. Which it's not what I would have liked, but I think this adds unnecessary complexity, I thought I was missing something obvious but maybe I'm not, I also have trouble searching for this. – Trufa May 24 '22 at 19:13
  • I don't think this is overkill, far from it in fact. It's probably the most basic canonical solution there is. – kelsny May 24 '22 at 21:38

0 Answers0