I have an async function inside an object, I need to declare type like the following example:
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: '',
};
How can I declare the type of a method in an object literal?
You can try one of these options :
const object1 = {
id: 235,
myTest: async ({pagination}) => {
console.log(`this = ${this}`);
console.log(`object1.id = ${object1.id}`, )
}
}
In this style, this
will be resolved to the globalThis
, which in this case is undefined
(see here ).
[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}`)
}
}
Which will output:
[LOG]: "this = {"id":813}"
[LOG]: "object2.id = 813"
[LOG]: "this.id = 813"
I found a solution usingParameters and NonNullable utilities.
const myObj = {
async myTest( {pagination} : Parameters<NonNullable<QTableProps['onRequest']> ) {
let $id = this.id;
// pagination is extracted
/* consume $id and await */
/* ... */
},
id: 521,
result: '',
};
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.