Home > Mobile >  how to coerce to specific subtype from union type
how to coerce to specific subtype from union type

Time:10-27

type example = {
    name : string | number | null
}
type processNumber = {
    name : number
}

const a : example = {
    name : 123
} as const
function PROCESS (input : processNumber) {
    console.log(input.name)
}

PROCESS(a);

I currently get the error

Argument of type 'example' is not assignable to parameter of type 'processNumber'.
  Types of property 'name' are incompatible.
    Type 'string | number | null' is not assignable to type 'number'.
      Type 'null' is not assignable to type 'number'.

How do coerce name to be of type number? Let us also assume that there are many more properties that need to be coerced, so anything that can quickly coerce (inline maybe) would be good.

CodePudding user response:

The fix is very easy:

type example = {
    name: string | number | null
}
type processNumber = {
    name: number
}

const a = {
    name: 123
} as const satisfies example

function PROCESS(input: processNumber) {
    console.log(input.name)
}

PROCESS(a);

Playground

All you need to do is to use satisfies operator. It allows you to check whether it is satisfies some particular type and also makes type inference.

Please keep in mind that satisfies was provided in most recent version 4.9 of typescript.

Also, since you are using as const assertion, you can get rid of satisfies, but also you have to get rid of explicit type annotation, like here:

const a = {
    name: 123
} as const
  • Related