Home > Back-end >  Typescript MarkNullable helper
Typescript MarkNullable helper

Time:11-16

Is there a way to create MarkNullable helper to mark some object properties as nullable?

Sandbox

type MarkNullable<T, K extends keyof T> = Omit<T, K> & Pick<T, K> /* how to mark as null? */;

type X = {
    a: number,
    b: number
}

type Y = MarkNullable<X, 'a'>

const y: Y = {} as any

y.a = null // a should be number | null
y.a = 1
y.b = 1

CodePudding user response:

Yes, you can use mapped types:


type X = {
    a: number,
    b: number
}
type MarkNullable<Obj, NullableKey> = {
    [Prop in keyof Obj]: Prop extends NullableKey ? Obj[Prop] | null : Obj[Prop]
}

type Y = MarkNullable<X, 'a'>

declare let y: Y

y.a // number | null
y.b // number

Playground

Please keep in mind, TS does not track mutations, hence in order to narrow y.a to number you should use if condition:

if(y.a){
 y.a // number
}
  • Related