打字稿根据参数返回不同的接口

时间:2020-04-15 23:29:58

标签: typescript typescript-typings

我想根据传递给方法的参数返回不同的接口。这是我到目前为止所拥有的:

interface A {
    a: string;
}
interface B {
    b: string;
}
interface C {
    c: string;
}

export enum Type {
  A = 'a',
  B = 'b',
  C = 'c',
}
interface Configs {
  a: A;
  b: B;
  c: C;
}

const get = <C extends Type>(name: C): Configs[C] => {
    if (name === Type.A) {
        return { a: 'true' } as A;
    }

    if (name === Type.B) {
        return { b: 'true' } as B;
    }

    if (name === Type.C) {
        return { c: 'true' } as C;
    }

    throw new Error('Unknown type')
}

// This works correctly
const b = get(Type.B);

该方法的使用正常进行;如果我做get(Type.B),我实际上会返回正确的界面。

但是,该方法本身在return语句上给了我错误,说property "x" is missing from A & B & C。如何编写此方法?

1 个答案:

答案 0 :(得分:3)

我们只能使用Config[C]作为返回类型。我们传递参数,然后泛型函数获取类型C,然后获取类型Config[C]

但是,您有3条带有差异类型ABC的return语句,因此编译器认为此函数的返回类型为A & B & C,然后抱怨{{ 1}}之类的东西。

因此,您应该只使用Type 'A' is not assignable to type 'A & B & C'作为返回类型,编译器就会知道它是什么类型。

Config[C]

您可以在这里看到游乐场:TypeScript Playground