React Native 在typescript中调用接口内部的其他方法

8xiog9wr  于 2023-03-24  发布在  React
关注(0)|答案(2)|浏览(142)

新手在这里打字。
我有用Typescript写的接口和方法。我想在另一个函数中调用另一个函数。我们如何在Typescript中做到这一点。

export interface InterfaceProps {
  someFunction1(): Promise<boolean>;
}

export const someClass: InterfaceProps {
 async someFunction1(): Promise<boolean> {
    someFunction2(); // This is not allowed right now. But how can i acheive this.
 }

 async someFunction2(): Promise<boolean> {
 }
}
qhhrdooz

qhhrdooz1#

我可以提出以下解决办法:

export interface InterfaceProps {
  someFunction1(): Promise<boolean>;
  someFunction2(): Promise<boolean>;
}

export const someClass1: InterfaceProps = {
 someFunction1: async(): Promise<boolean> => {
    return someClass1.someFunction2() // function call in the someFunction1 and return Promise boolean
 },
 someFunction2: async (): Promise<boolean> => Promise.resolve(true), // Function return Promise boolean
}

// OR

export const someClass2: InterfaceProps = {
 someFunction1: async(): Promise<boolean> => {
    someClass2.someFunction2() // function call in the someFunction1
    return Promise.resolve(true) // return Promise boolean
 },
 someFunction2: async (): Promise<boolean> => Promise.resolve(true), // Function return Promise boolean
}

请注意,我使用箭头功能,我建议你这样做。
Playground

nhjlsmyf

nhjlsmyf2#

你得到错误,因为你为someFunction1定义了Promise<boolean>类型返回值,你应该在函数的末尾返回一个promise(布尔类型),你也忘记在InterfaceProps接口中定义someFunction2

export interface InterfaceProps {
  someFunction1(): Promise<boolean>;
  someFunction2(): Promise<boolean>;
}

export const someClass: InterfaceProps = {
  async someFunction1(): Promise<boolean> {
    return await this.someFunction2();
  },
  async someFunction2(): Promise<boolean> {
    return new Promise(resolve => setTimeout(() => resolve(true), 1000));
  },
};

但是如果你不想返回一些东西并假设为void,那么就像下面这样做:

相关问题