简体   繁体   中英

How to define a Typescript type using generics

Let's say I have the following interface defining an object:

interface ExampleInterface {
    a: string:
    b: number;
    c: AsyncFunction<boolean>
}

where AsyncFunction is defined by:

type AsyncFunction<T> = () => Promise<T>;

This currently works well if the function supplied to c: has no parameters, but causes a TS2322 compilation error if the function has any parameters.

The idea is that <T> is used to define the return type within the Promise of the function. The function may or may not need its own parameters, but it must provide the specified T return type within a Promise.

My question is, is there a way to modify the type definition so that any function with zero or any number of parameters of any fashion can be used in c :?

I've tried to understand infer but all of my attempts to use it (and it may not be what I'm looking for) have ended up with c : having an (any) return type which is not what I want. I've also tried using the following with no success.

type AsyncFunction<T> = (...args: any[]) => Promise<T>;

Thanks in advance.

Your example "tried the following with no success works perfectly":

Playground

Thanks to @Rubydesic making me walk through everything to provide more details, I realised I was being an idiot.

The reason it wouldn't compile had nothing to do with the type definition - that didn't actually need changing.

The issue was that with no parameters, I was simply passing the method name into c:

async function foo(): Promise<boolean> {
// Body omitted
}

const x: ExampleInterface = {
a: 'a',
b: 0,
c: foo
}

Of course, this worked, but when the method had parameters I was then passing those in (which because of the need for brackets would be attempting to execute it, not passing it in - the part I failed to realise after a long day - talk about missing the obvious). I was doing:

async function bar(a: number): Promise<boolean> {
// Body omitted
}

const x: ExampleInterface = {
a: 'a',
b: 0,
c: bar(0)
}

When I should have been doing

async function bar(a: number): Promise<boolean> {
// Body omitted
}

const x: ExampleInterface = {
a: 'a',
b: 0,
c: () => bar(0)
}

Answer posted as a painful reminder to take a break every so often. In 10 years, I don't think I've ever been quite so blind to the problem!

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