gpt4 book ai didi

typescript : how to make type system accurately determine output type based on inputs using

转载 作者:行者123 更新时间:2023-12-04 03:43:33 24 4
gpt4 key购买 nike

类型系统存在问题,无法根据输入准确确定输出类型。

使用的类型:

type inputs = "alpha" | "beta" | "gamma";

type AlphaSchema = {
pet: string,
house: string
}

type BetaSchema = {
boss: string,
work: string,
}

type GammaSchema = {
monk: string,
temple: string,
}

type Schemas = {
'alpha': AlphaSchema,
'beta': BetaSchema,
'gamma': GammaSchema
}

type BuilderStore = {
buildersFor: {
[key in inputs] : {
build: (str1: string, str2: string) => Schemas[key]
}
};
}

工作示例:


const exampleSchemaResults = {
'alpha' : {pet: 'scooby', house: 'West Garden Home'},
'beta' : {boss: 'Jake', work: 'The Royal Palace'},
'gamma' : {monk: 'Tai', temple: 'Shaolin'},
}

const getExampleSchema: <T extends inputs>(input: T) => Schemas[T] = (input) => exampleSchemaResults[input];

const alphaExample = getExampleSchema('alpha');

在这种情况下,typescript 能够准确地确定获得的结果将是 AplhaSchema

类型

无法解析的示例:

const store: BuilderStore = {
buildersFor : {
'alpha': {
build: (str1: string, str2: string): AlphaSchema => { return {pet: str1, house: str2} },
},
'beta': {
build: (str1: string, str2: string): BetaSchema => { return {boss: str1, work: str2} },
},
'gamma': {
build: (str1: string, str2: string): GammaSchema => { return {monk: str1, temple: str2} }
}
}
}

const getBuilder = <T extends inputs>(input : T) => store.buildersFor[input];

const build = <T extends inputs>(input: T, str1: string, str2: string) => getBuilder(input).build(str1, str2);

const schema = build('alpha', 'scooby', 'West Garden Home');

这里的问题是获得的最终模式是类型:

AlphaSchema |测试架构 | GammaSchema

我希望它是这样的:

AlphaSchema

我理解这段代码使用构建函数生成模式,但这不应该像上面提到的工作片段那样解决吗?

我们能否不根据输入解析输出模式(假设通用中使用了“alpha”)?或者这是不可能的?

函数的输入方式有问题吗?

TS playground link

最佳答案

有趣的行为。我也希望它能起作用。在我看来,当 TS 静态创建 getBuilder(input).build 的“类型”时它不知道将调用哪个构建器函数。如果将显式返回类型添加到 build函数,您可以更清楚地看到错误。

const build = <T extends inputs>(input: T, str1: string, str2: string): Schemas[T] => getBuilder(input).build(str1, str2);

TS error

这似乎证实了 TS 不知道哪个 build函数将被调用,所以返回类型是所有这些。要修复它,您可以将返回类型转换为正确的架构:

const build = <T extends inputs>(input: T, str1: string, str2: string): Schemas[T] => (getBuilder(input).build(str1, str2) as Schemas[T]);

这会删除所有错误并给出最终的 schema变量正确的类型。

关于 typescript : how to make type system accurately determine output type based on inputs using <generics>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65549744/

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