1
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.

1
  • Maybe something like PROCESS(a as processNumber ); would work. Oct 26, 2022 at 6:31

1 Answer 1

2

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
1
  • I like the satisfies operator, as it allows me to use the explicit type annotation, which has type inferences
    – A. L
    Oct 26, 2022 at 13:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.