dps
dps

Reputation: 864

Optional<T, Props> generic type in TypeScript

I'm trying to create type Optional<T, TProps> where T - initial type, TProps - union type of properties that have to be optional.

For example:
type A = Optional<{a: string, b: string}, 'a'>
const a: A = {b: 'foo'} // No Error

I expected this to work but It's not working type Optional<T extends object, TProps extends keyof T> = {[TKey in keyof T]: TKey extends TProps ? T[TKey] | never : T[TKey]}

Upvotes: 2

Views: 329

Answers (1)

Dmitry McLygin
Dmitry McLygin

Reputation: 94

According to your code above, I think you need to concat Exclude and Pick solutions.

I was playing with them and seems, the following solution works:

type Optional<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>> & Partial<Pick<T, K>>

the example below will show an error, if you want to add to b incorrect field and won't highlight if you remove the optional parameter:

interface BI {
  a: number
  b: number
  g: string,
  f: boolean
}

const a: BI = {a: 1, b: 2, g: 'sdf', f: true}

const b: Optional<BI, 'g'> = {a: 5, b: 1, f: true}

Upvotes: 2

Related Questions