【问题标题】:TypeScript - omit generic's extended typeTypeScript - 省略泛型扩展类型
【发布时间】:2020-09-12 11:58:45
【问题描述】:

我对 typescript 中的 omit 有疑问。当我尝试从 TMutationVariables 中省略 commandId 时,它会引发 TS 错误:

TS2345: Argument of type 'Pick<TMutationVariables, Exclude<keyof TMutationVariables, "commandId">> & { commandId: string; }' is not assignable to parameter of type 'TMutationVariables'.   'Pick<TMutationVariables, Exclude<keyof TMutationVariables, "commandId">> & { commandId: string; }' is assignable to the constraint of type 'TMutationVariables', but 'TMutationVariables' could be instantiated with a different subtype of constraint '{ commandId: string; }'.
export function createQueryWithSubscription<TMutationVariables extends {commandId: string}>(
    query: string,
): (variables: Omit<TMutationVariables, "commandId">) => any {
    const sendQuery = (changes: TMutationVariables): any =>
        gqlCommand<TMutationVariables>(
            query, changes as any
        );

    return function processQueryWithSubscription(
        variables
    ) {
        return async (dispatch: any) => {
            const commandId = generateUuid();
            //error occurs in declaration BELOW
            const completedVariables: TMutationVariables = {
                ...variables,
                commandId
            };
            const commandFinished = await dispatch(sendQuery(completedVariables));
        };
    };
}

我有从 graphql 架构创建的类型(包括 commandId 到订阅),但是从外部我需要从这个架构创建的所有变量,除了 commandId(因为我在 process 函数中加入了 commandId)。

现场样本: https://www.typescriptlang.org/play#code/KYDwDg9gTgLgBAMwK4DsDGMCWEVzVYAQxmAEUlgoBPAdUxgAsBlJAIwGd9MwscAeACoBZJDGLYUANUJRMhVgBtg7OKBIoAJioDeaCAFt9hTQEkNALjjsYslAHMAvgD4AFACgAkAEcK1S9ds7ABo3AEpLFwA3GTlFZUsAeX16QRExXikY+SV2ILgAIj1DYw0zfKdQuABeJzhjKjhtTz0UaytgTXJKBqq4FzQGYzt4uGFRcRxpWWzlcLqUHqdPDzsvBQBhAyNNPnrXZe9fKjyBoeU6lXrl0IBuN08CGCQoXGR0DLgwKAg0ZXYu6h0RgsDhcHgSdweDzRaZxdieSpNKGPZ64QjsKjoPoaTDsMDEAaWeqVGqNA4tNpFbalDTVODDFCUYjAACqSEwGhct3JOEpBjAShIGimsRyljG6QkIpmKl6SKhHgAdMqYaLlCEFR4qSUzAcHHcFRT4NrNAAxTAoXEMYC03qEADuhHocBxeIJDBc7A6GgBVH6-MFNulcNC3Kh+s8EYcbiAA

有什么帮助吗?谢谢

【问题讨论】:

    标签: javascript typescript redux graphql


    【解决方案1】:

    而不是在函数签名类型中使用“扩展”

    export function createQueryWithSubscription<TMutationVariables extends {commandId: string}>(
    

    你应该像这样合并声明:

    type TMutationVariablesWithCommandId = TMutationVariables & {commandId: string};
    export function createQueryWithSubscription<TMutationVariablesWithCommandId>(
    

    Playground Link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-01
      • 2023-01-12
      相关资源
      最近更新 更多