Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

124
Views
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'

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!