Home > Back-end >  Is there a reason why this code is casting to 'unknown' as an intermediary type?
Is there a reason why this code is casting to 'unknown' as an intermediary type?

Time:03-24

I'm reading through the source code for this repo: https://github.com/cwayfinder/on-property-change/blob/master/src/on-property-change.ts

and I see:

function normaliseProps(props: string | string[]): string[] {
    if (Array.isArray(props)) {
        return props as unknown as string[];
    } else {
        return [props as unknown as string];
    }
}

Is there any reason for casting to unknown here?

As far as I can tell, it can be removed:

function normaliseProps(props: string | string[]): string[] {
    if (Array.isArray(props)) {
        return props as string[];
    } else {
        return [props as string];
    }
}

Is there any benefit of using the former code?

CodePudding user response:

Type assertions so require some relationship between the source and target type. So you can't assert a string is a number (ex). The common escape hatch for this is to assert to unknown first and then you can assert to anything

let v: string = "";
let n = v as unknown as number

Playground Link

In your case string and string[] are subtypes of string | string[] so no assertion to unknown is actually required.

More over since you are using Array.isArray which is a type guard no assertion is required at all:

function normaliseProps(props: string | string[]): string[] {
    if (Array.isArray(props)) {
        return props;
    } else {
        return [props];
    }
}

Playground Link

  • Related