[英]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.