Typescript在对象中创建一个函数,返回接口关联键的类型



我想知道是否有办法在typescript中做到这一点。假设我有这样一个接口:

interface Transaction {
amount: number;
order_date: Date;
id: string;
}

我想创建一个名为Mapper的类型,它将为外部API接收的json的每个键映射到我自己的接口,例如:

const ExternalAPIMapper: Mapper = {
amount: (raw_transaction) => raw_transaction.sale_amount,
order_date: ({ transaction_date }) => dayjs(transaction_date, 'YYYY.MM.DD').toDate()),
id: ({ transaction_id }) => transaction_id
}

我创建了以下类型:

type Mapper = Record<keyof Transaction, ((t: any) => any)>

但是这个类型的问题是我的函数可以返回任何类型。我希望该函数被键入以返回与键关联的类型。这可能吗?

如果它工作,我可以映射JSON的任何外部API只是与映射器和这个函数:

const mapNetworkTransaction = (
object: Record<string, string>,
mapper: Mapper,
): Transaction => {
const txn = { };
for (let i = 0; i < txnFields.length; i++) {
const txnField = txnFields[i];
const accessor = mapper[txnField];
if (accessor) {
txn[txnField] = accessor(object);
}
}
return txn;
};

您应该使用映射类型。

type Mapper = {
[K in keyof Transaction]: (t: any) => Transaction[K]
}

生成的类型如下:

type Mapper = {
amount: (t: any) => number;
order_date: (t: any) => Date;
id: (t: any) => string;
}
游乐场

最新更新