Home > Mobile >  How to type cast in Typescript? Is it an 'as?' operator?
How to type cast in Typescript? Is it an 'as?' operator?

Time:07-20

This line is not accepted:

const oid: string | undefined = keyPath[0]

bacause, keyPath array can have number or string elements.

Type 'string | number' is not assignable to type 'string'.
  Type 'number' is not assignable to type 'string'.

I tried also this:

const oid?: string = keyPath[0]

In Swift I could use an as? operator. Does it exist in Typescript. It would try to cast to i.e. string, if not possible then it return an undefined. What about Typescript. Does it exist similar operator?

CodePudding user response:

I found:

const oid: string | undefined = keyPath ? (keyPath[0] as string) : undefined

CodePudding user response:

There is an as operator in typescript. However, this does not cast the value at runtime like you may expect. It just tells the typescript compiler that this can be treated as string. The code below will compile, but the value of bar is still a number:

const foo: number = 1;
const bar: string = foo as string;
console.log(bar); // This will output the number 1 (not the string '1')

If you really want to check the type at runtime, you can use the typeof operator like this:

const key: string | number = keyPath[0]
const oid: string | undefined = typeof key === 'string' ? key : undefined;

This code does really perform a runtime check so you can be sure keyPath[0] is actually a string. The typescript compiler does also understand this expression and will narrow the type correctly.

  • Related