Leo Jiang
Leo Jiang

Reputation: 26095

Typescript cast function argument type

Right now, I'm doing:

function fn(arg) {
  const foo = arg as SomeType;
  ...
}

Is there a way to do the type casting in the function argument? I.e. something like function fn(arg as SomeType)

Here's an example:

Promise.race([
  Promise.resolve(1),
  new Promise((_, fail) => {
    setTimeout(fail, 1000);
  }),
])
  .then((res: number) => {
    ...
  });

But TS throws:

Argument of type '(res: number) => void' is not assignable to parameter of type '(value: unknown) => void | PromiseLike<void>'.
  Types of parameters 'res' and 'value' are incompatible.
    Type 'unknown' is not assignable to type 'number'

Instead, I have to do:

.then((temp) => {
  const res: number = temp as number;
  ...
});

Upvotes: 3

Views: 4768

Answers (3)

Grabofus
Grabofus

Reputation: 2034

In the example you're racing Promise<number> and Promise<unknown>, if you know that your second promise always fail (used for timeouts) you can type it as Promise<never>.

This would ensure that you cannot actually resolve the promise, as there is no possible value _ would accept.

Promise.race([
  Promise.resolve(1),
  new Promise<never>((_, fail) => {
    setTimeout(fail, 1000);
  }),
])
  .then((res: number) => {
    ...
  });

Upvotes: 2

Miguel Gozaine
Miguel Gozaine

Reputation: 1

function fn(arg: SomeType) {
  ...
}

And if you want to be sure that the function is returning exactly te type of value you need, u should put it just after the argument, something like this:

function fn(arg: SomeType): SomeType {
  return const foo = arg;
}

This way you make sure the compiler tells you when the function is returning a value that is not of the type you wanted.

Upvotes: 0

mdrichardson
mdrichardson

Reputation: 7241

TypeScript doesn't have "type casting" so much as "type asserting" since it doesn't change runtime behavior, at all. There's no way to "cast" a type in a function argument. However, you can "assert"/require it when developing with something like:

function fn(arg: SomeType) {
  ...
}

More info:

Type assertions are a way to tell the compiler “trust me, I know what I’m doing.” A type assertion is like a type cast in other languages, but performs no special checking or restructuring of data. It has no runtime impact, and is used purely by the compiler. TypeScript assumes that you, the programmer, have performed any special checks that you need.

Upvotes: 1

Related Questions