Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript notation async function as type/interface attribute

I'm having trouble with the syntax for an async (arrow) function as a type/interface attribute. I've already done a bit of research but didn't found much except this https://github.com/Microsoft/TypeScript/issues/22035 It's not 100% accurate to my case but better than nothing. And still doesn't work for me...

Here is about the code I have in the declaration (simplified) :

export type MyType = {
    att1: string;
    funct: async (param1: string, param2: string) => Promise<string[]>;
};

And where I use it (example, not my actual code) :

import { MyType } from "./MyType";

const myObject: MyType = {
    att1: "First attribute";
    funct: async (param1: string, param2: string): Promise<string[]> => {
        // Code below is an example, in my case it's a database querying
        // But anyway, it's something async
        return new Promise((resolve, reject): void => {
            setTimeout((): void => {
                resolve(["string1", "string2"]);
            }, 5000);
        });
    };
};

The TypeScript transpiler says it cannot find the name "async". How do I tell the function "funct" in MyType is async? I need to use await in it...

like image 496
Ascor8522 Avatar asked Jan 26 '19 20:01

Ascor8522


People also ask

How to type an async function in typescript?

To type an async function in TypeScript, set its return type to Promise<type>. Functions marked async are guaranteed to return a Promise even if you don't explicitly return a value, so the Promise generic should be used when specifying the function's return type. Copied!

What is interface in typescript?

Interface can define both the kind of key an array uses and the type of entry it contains. Index can be of type string or type number. An interface can be extended by other interfaces. In other words, an interface can inherit from other interface. Typescript allows an interface to inherit from multiple interfaces.

Can typescript infer the type of an argument?

If you do not want to specify types at all, TypeScript’s contextual typing can infer the argument types since the function value is assigned directly to a variable of type SearchFunc. Here, also, the return type of our function expression is implied by the values it returns (here falseand true).

What are the different types in typescript?

Explore how TypeScript extends JavaScript to add more safety and tooling. Primitives Any Literals Union and Intersection Types Unknown and Never Type Primitives Tuples Built-in Utility Types Nullable Types Meta-Types Conditional Types Discriminate Types Indexed Types Mapped Types Language Soundness Structural Typing Type Guards


Video Answer


1 Answers

The answer is simple, you don't tell the compiler the function is async on the interface. async is an implementation detail, it allows you to use await inside the body of the function. The user of the interface does not care how you implement your function only what it returns and what parameters need to be passed in.

What you really want is to tell the compiler that the function does not return string[] but rather a Promise<string[]>. This means that the caller can't access the result directly but needs to either use then on the returned promise or use await to get the result.

export type MyType = {
    att1: string;
    funct:  (param1: string, param2: string) => Promise<string[]>;
};
like image 196
Titian Cernicova-Dragomir Avatar answered Oct 04 '22 22:10

Titian Cernicova-Dragomir