简体   繁体   中英

Restricting Return Type Of Function in TypeScript

Let's say I have the following class.

class MyClass {
  firstMethod: (a: string) => string;
  secondMethod: (b: number) => number;
}

I want to create a function, which accepts this class as its first argument. This should inform the type of the return type of the second argument, a function. Regardless of structural typing, I hope to restrict the return type fields to be of those defined in MyClass. For instance:

Good:

myFunction(MyClass, () => {
  return {
    firstMethod: (a) => a,
    secondMethod: (b) => b,
  };
});

Bad:

myFunction(MyClass, () => {
  return {
    firstMethod: (a) => a,
    secondMethod: (b) => b,
    thirdMethod: (c: boolean) => c,
  };
});

The extra field should result in a type error. As should altering the types of firstMethod and secondMethod .

Right now, I'm trying unsuccessfully like this .

Any help would be greatly appreciated. Thank you!

is this what you want?

const myFunction = (a : MyClass): MyClass => {
  return {
    firstMethod: (a: string) => a,
    secondMethod: (b: number) => b,
  };
}

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