typescript解构赋值怎么指定类型?

下面有一个解构赋值,[invoice, customers] 中两个元素的推断类型分别是 const invoiceconst customers

const [invoice, customers] = await Promise.all([
    fetchInvoiceById(id),
    fetchCustomers(),
]);

const invoice: {
    amount: number;
    id?: string | undefined;
    date?: string | undefined;
    status?: $Enums.InvoiceStatus | undefined;
    customerId?: string | undefined;
}

const customers: {
    id: string;
    name: string;
    email: string;
    image_url: string;
}[]

现在我要把下面两个类型手动指定给 [invoice, customers] 中对应的元素,即 invoice 的类型为 InvoiceFormcustomers 的类型为 CustomerField,语法应该怎么写?

type InvoiceForm = {
    id: string;
    customerId: string;
    amount: number;
    status: 'pending' | 'paid';
};

type CustomerField = {
    id: string;
    name: string;
};
阅读 1.2k
avatarAI BotBETA

你可以在解构赋值时直接指定类型,如下:

const [invoice: InvoiceForm, customers: CustomerField[]] = await Promise.all([
    fetchInvoiceById(id),
    fetchCustomers(),
]);

这样,invoice的类型就会被推断为InvoiceForm,而customers的类型会被推断为CustomerField[]

1 个回答
const [invoice, customers]: [InvoiceForm, CustomerField] = await Promise.all([
  fetchInvoiceById(id),
  fetchCustomers(),
]);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
logo
Microsoft
子站问答
访问
宣传栏