Home > database >  Getting a type error when writing a function: Argument of type 'string | undefined' is not
Getting a type error when writing a function: Argument of type 'string | undefined' is not

Time:08-24

I'm writing a function that extracts the last character of a string, then converts it to number. However, TypeScript returns an error about the string possibly being undefined. But how could that be possible, given that I had predefined the type?

type DogName = "dog1" | "dog2" | "dog3"

const parseDogNumber = (dogName: DogName): number => {
    const dogNumber = dogName.at(-1) // this returns a string
    const asInt = parseInt(dogNumber) // this returns a number
//                           ^^^^^
// Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
//   Type 'undefined' is not assignable to type 'string'.(2345)
     

    return asInt
}

One way I can circumvent the error is by explicitly specifying as string for the type of dogNumber:

const parseDogNumber2 = (dogName: DogName): number => {
    const dogNumber = dogName.at(-1) as string 
    const asInt = parseInt(dogNumber) // this returns a number
    return asInt
}

But I still don't understand why I am getting the error in the first place, even though I typed DogName specifically, leaving no room for undefined.


TS playground here

CodePudding user response:

This is because when you use String.prototype.at, TypeScript uses built in type of at method:

String.at(index: number): string | undefined

It means that if even you are 100% sure that It should return string, TS still think that it is string | undefined.

  • Related