- TypeScript types typescript
Original story https://twitter.com/teramotodaiki/status/1214149145935532033
ts
key
- get2
- Since
keyof typeof obj
==="s" | "f"
. (parameter) key: "s" | "f"
- Since
- get4
(parameter) key: Key extends "s" | "f"
const value = obj[key]
- get2
const value: string | (() => string)
- get6 ts
In short, the original code does not know that the key type is "s" | "f"
because of the extra extensions,
As a result, obj[key]
is also not recognized as string | (() => string)
.
If it is string | (() => string)
, it is a Union Type, so you can use [Type Guards https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and- differentiating-types] can be used, but get6 is a complex type and cannot be used.
(Possible but not supported by TS at this time)
So the value in the else clause is not found to be () => string
and Type 'string' has no call signatures
.
const x = get2("f") // const x: string | (() => string)
Hmmm, well, that’s right, the obj could be rewritten before the function is called.
ts
If you want this kind of behavior,
ts
would it be better to … or …
Practice type (e.g. of machine, goods, etc.) in [TypeScript
This page is auto-translated from /nishio/TypeScriptの型の練習 using DeepL. If you looks something interesting but the auto-translated English is not good enough to understand it, feel free to let me know at @nishio_en. I’m very happy to spread my thought to non-Japanese readers.