'Use keyof on optional field
I would like to use keyof to describe the parameters of a function, based on an optional field in a Object. And I would like to add a default value.
interface foo {
bar?: {
opt1: string,
opt2: string
}
}
function func(option: keyof foo["bar"] = "opt1") ...
But as bar is optional i got Type 'string' is not assignable to type 'never'
Solution 1:[1]
You can get rid of the possibility of undefined by using NonNullable:
function func(option: keyof NonNullable<foo["bar"]> = "opt1")
Note that the above will also get rid of the possibility of null, which may or may not be desired. Another option is you could use Exclude, which is more verbose but gives you more flexibility:
function func(option: keyof Exclude<foo["bar"], undefined> = "opt1")
For more info on these utility types, see this page: https://www.typescriptlang.org/docs/handbook/utility-types.html
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
