繁体   English   中英

object 文字中的方法类型定义

[英]Method type definition inside object literal

我在 object 中有一个异步 function,我需要像以下示例一样声明类型:

interface Props {
  loading?: boolean | undefined;
  separator?: 'cell' | 'none';
  onRequest?: (requestProp: {
    pagination: {
      sortBy: string;
      descending: boolean;
      page: number;
      rowsPerPage: number;
    };
    filter: string;
  }) => void;
}

const myObj = {
  async myTest({ pagination }) {  // I need to assign myTest as Props['onRequest']
  let $id = this.id;
      /* consume $id and await */
      /* ... */
  },
  id: 521,
  result: '',
};

如何在 object 文字中声明方法的类型?

您可以尝试以下选项之一:

使用箭头函数

const object1 = {
    id: 235,
    myTest: async ({pagination}) => {
        console.log(`this = ${this}`);
        console.log(`object1.id = ${object1.id}`, )
    }
}

在这种风格中, this将被解析为globalThis ,在这种情况下它是undefined的(见这里)。

[LOG]: "this = undefined" 
[LOG]: "object1.id = 235" 

使用常规函数

const object2 = {
    id: 813,
    myTest: async function({pagination}) {
        console.log(`this = ${JSON.stringify(this)}`);
        console.log(`object2.id = ${object2.id}`, )
        console.log(`this.id = ${this.id}`)
    }
}

这将输出:

[LOG]: "this = {"id":813}" 
[LOG]: "object2.id = 813" 
[LOG]: "this.id = 813" 

我找到了使用参数和 NonNullable实用程序的解决方案。

    const myObj = {
      async myTest( {pagination} : Parameters<NonNullable<QTableProps['onRequest']> ) {  
      let $id = this.id;
          // pagination is extracted
          /* consume $id and await */
          /* ... */
      },
      id: 521,
      result: '',
    };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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