Home > front end >  Why does the type ( () => string ) appear out of nowhere?
Why does the type ( () => string ) appear out of nowhere?

Time:11-12

I'm working with the jasonwebtoken package. I came across this new javascript/typescript behaviour.

interface JwtPayload {
    [key: string]: any;
    iss?: string | undefined;
    sub?: string | undefined;
    aud?: string | string[] | undefined;
    exp?: number | undefined;
    nbf?: number | undefined;
    iat?: number | undefined;
    jti?: string | undefined;
}
let payload: JwtPayload | string
let id: string | undefined

id = payload.sub

At the assignment I get the error. What is going on?

Type 'string | (() => string) | undefined' is not assignable to type 'string | undefined'.
Type '() => string' is not assignable to type 'string'.(2322)

TS Playground

CodePudding user response:

You've declared payload as either a JwtPayload or a string:

let payload: JwtPayload | string

That means payload.sub can either mean the sub property of JwtPayload or the sub property of string.

Turns out sub on a string exists: it's the String.prototype.sub() method, which has the type () => string. So it doesn't come from nowhere.

To assign payload.sub to id, you'll need to make sure payload is not a string:

if (typeof payload !== 'string') {
    id = payload.sub;
}

That way the compiler can safely determine that it is a JwtPayload, which means payload.sub has the type you want.

You can also just assert that payload has the type you assume it has, but that just means telling the compiler to shut up about type safety, which means you'll need to cross your fingers it won't give out an error at runtime.

  • Related