简体   繁体   中英

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? Ie 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;
  ...
});

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.

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) => {
    ...
  });
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM