gpt4 book ai didi

typescript - 某些成分中的冲突类型

转载 作者:行者123 更新时间:2023-12-05 04:46:40 24 4
gpt4 key购买 nike

我试图让一个方法根据作为参数给出的字符串返回特定类型。这是我的:

interface Base {
type: 'a' | 'b';
}

interface MyA extends Base {
type: 'a';
nameA: string;
}

interface MyB extends Base {
type: 'b';
nameB: string;
}

interface Mappings {
a: MyA;
b: MyB;
}

const testMethod = <K extends keyof Mappings>(
type: K
): Mappings[K][] => {
const values: Mappings[K][] = [];

if(type === 'a') {
values.push({
type: 'a',
nameA: 'My name a'
});
}
else if(type === 'b') {
values.push({
type: 'b',
nameA: 'My name b'
});
}

return values;
}

因此,如果我运行 testMethod('a'),它的返回类型将是 MyA[],当我使用 testMethod('b') 它将返回 MyB[]。但无论我做什么,我都无法让它发挥作用。错误总是:

Argument of type 'MyA' is not assignable to parameter of type'Mappings[K]'. Type 'MyA' is not assignable to type 'never'.The intersection 'MyA & MyB' was reduced to 'never' because property 'type' has conflicting types in some constituents.

我认为数组可能是问题所在,但返回 Mappings[K] 类型的变量也有同样的问题。 Here是 Playground 链接。我过去做过类似的事情 this一个根据作为参数给出的字符串修改函数的参数,但在这里我完全迷路了。

如果我能阅读任何指南或 typescript 资源,我们将不胜感激!

最佳答案

奇怪的是,一旦我指定映射扩展 Record<string, MyA | MyB>,这对我就起作用了.我删除了共同祖先 Base,因为它似乎没有帮助。

interface MyA {
type: 'a';
nameA: string;
}

interface MyB {
type: 'b';
nameB: string;
}

interface Mappings extends Record<string, MyA | MyB> {
a: MyA;
b: MyB;
}

// same as above

const arrayOfMyA = testMethod('a'); // typed as MyA[]
const arrayOfMyB = testMethod('b'); // typed as MyB[]

我没有直观的解释,除了显式联合是让 TypeScript 相信 'a' | 'b' 的唯一方法。 ( keyof Mappings ) 详尽地导致 MyA | MyB ...尽管Mappings[keyof Mappings]正确结果为 MyA | MyB改变之前和之后!这可能是一个 TypeScript 错误,或者至少是一个改进的机会。

type MappingResults = Mappings[keyof Mappings];
// typed as MyA | MyB, regardless of whether
// Mappings extends Record<string, MyA | MyB>!

Playground Link

关于typescript - 某些成分中的冲突类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68749867/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com