最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to Flatten an Object Type Definition in Typescript - Stack Overflow

programmeradmin3浏览0评论

There are some functions in my backend api, which accept a requestOrigin as an argument. If the requestOrigin is equal to "web", I grab all other parameters and send them to another function, which generates an OTP, saves the parameters values inside a database along with the OTP, and sends it to the User via phone or email. When the user confirms it, it gets the same previously saved parameters value and calls the original function. Now these parameters can be objects too. To create the sql statement I have a generic function. My problem is that I want to create a table type object that depends on the functions parameters that are passed to the webRequestValidation function. For this reason, whenever I have a parameter object type, that also contains properties that are themselves objects, i want to replace such property name with its own properties. In other words, I want to flatten the object type. I want to create a generic function that allows me to do so.

For instance, this is one type for one of my functions:

type TransferFundsParams = Parameters<AppManager["transferFunds"]>[0];

When I over the mouse on it, it appears like this:

type TransferFundsParams = {
    emitterData: Omit<EmitterData, "emitterTelephone">;
    receiverData: ReceiverData;
    amount: number;
    requestOrigin: RequestOrigin;
    refunding?: {
        transactionID: string;
    };
}

I have created a Flatten generic type as follows:

type Flatten<T> = T extends object ? {[P in keyof T]: T[P] extends object ? Flatten<T[P]> : T[P]} : T;

When I call it on the initial: TransferFundsParams

type FlattenTransferFundsParams = Flatten<TransferFundsParams>
type FlattenTransferFundsParams = {
    emitterData: {
        emitterClientID: string;
        emitterCountry: Country;
        emitterAccountType: AccountType;
        emitterTokenIssuedAt: number;
        emitterAccountStatus: AccountStatus;
    };
    receiverData: {
        receiverClientID: string;
        receiverCountry: Country
    };
    amount: number;
    requestOrigin: RequestOrigin;
    refunding?: {
        transactionID: string;
    } | undefined;

That is not the desired result. RequestOrigin, AccountStatus, AccountType and Country are literal Union types. So I want to keep them. I was expecting to get the type as follows:

type FlattenTransferFundsParams = {
    emitterClientID: string;
    emitterCountry: Country;
    emitterAccountType: AccountType;
    emitterTokenIssuedAt: number;
    emitterAccountStatus: AccountStatus;
    receiverClientID: string;
    receiverCountry: Country
    amount: number;
    requestOrigin: RequestOrigin;
    transactionID: string;
}
    
发布评论

评论列表(0)

  1. 暂无评论