【问题标题】:TypeScript union type allowing values outside of type [duplicate]TypeScript联合类型允许类型之外的值[重复]
【发布时间】:2021-06-13 16:04:47
【问题描述】:

我希望我的标题是明确的,但我对 TS 比较陌生,而且我正在努力处理联合类型。

我正在尝试创建一个通用的callApi 函数,它允许可选的pagingfilters 查询参数。但是,我想让过滤器选项强类型,例如,当调用/api/people/时,我只想允许PeopleFilterQueryParams

这是我到现在为止的想法,但是,它允许 idafter 过滤器查询参数 - 当它应该只允许两者之一时。

export type BookingQueryParams = {
    before?: string;
    after?: string;
}

export type PersonQueryParams = {
    id?: number;
}

export type FilterQueryParams = BookingQueryParams | PersonQueryParams;

export interface PaginationQueryParams {
    page?: number;
    size?: number;
}

export interface ApiRequestParams {
    filters?: FilterQueryParams;
    paging?: PaginationQueryParams;
}

export const callApi = (url: string, params?: ApiRequestParams) => {
    return ``;
}

callApi('/people', {
    filters: {
        id: 123,
        after: '',
    }
})

我在这里有一个 TS 游乐场链接来展示我的问题: TS playground

任何帮助将不胜感激!

【问题讨论】:

    标签: typescript


    【解决方案1】:

    我相信这是因为嵌套联合的一些错误。找不到github问题。

    但是,有一个解决方法。

    export type BookingQueryParams = {
        before?: string;
        after?: string;
    }
    
    export type PersonQueryParams = {
        id?: number;
    }
    
    type UnionKeys<T> = T extends T ? keyof T : never;
    type StrictUnionHelper<T, TAll> = 
        T extends any 
        ? T & Partial<Record<Exclude<UnionKeys<TAll>, keyof T>, never>> : never;
    
    // credits goes to https://stackoverflow.com/questions/65805600/struggling-with-building-a-type-in-ts#answer-65805753
    type StrictUnion<T> = StrictUnionHelper<T, T>
    
    export type FilterQueryParams = StrictUnion<BookingQueryParams | PersonQueryParams>;
    
    export interface PaginationQueryParams {
        page?: number;
        size?: number;
    }
    
    export interface ApiRequestParams {
        filters?: FilterQueryParams;
        paging?: PaginationQueryParams;
    }
    
    export const callApi = (url: string, params?: ApiRequestParams) => {
        return ``;
    }
    
    callApi('/people', {
        filters: {
            id: 123,
            after: '', // error
        }
    })
    

    Credits goes toTitian Cernicova-Dragomir

    你只需要让联合更加严格

    【讨论】:

    • 有趣的阅读材料。这似乎可以解决问题。感谢您的快速响应!
    • @nbokmans btw,我有一个博客catchts.com,我写了几篇关于与工会合作的文章。我敢打赌你会发现一些有趣的例子。我所有的文章都是基于 StackOverflow 问题/答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-11
    • 2021-01-31
    • 2018-07-26
    • 2020-02-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多