繁体   English   中英

TypeScript 索引属性与推断的通用类型不匹配

[英]TypeScript indexed property not matching inferred generic type

此代码无法编译:

type Validator<T> = (value: string) => { value: T }

const createValidator = <TState extends any>(state: TState) =>
    <TName extends keyof TState>(x: TName, validator: Validator<TState[TName]>) => {
        return (value: { [P in TName]: string }): { [P in TName]: TState[TName] } => {
            const result = validator(value[x]);

            return { [x]: result.value };
        };
    }

return { [x]: result.value }; 给我Type '{ [x: string]: TState[TName]; }' is not assignable to type '{ [P in TName]: TState[TName]; }'. Type '{ [x: string]: TState[TName]; }' is not assignable to type '{ [P in TName]: TState[TName]; }'. 即使 TName 是从 x 推断出来的。

这是为什么? 我能做些什么 - 除了强制转换返回值?

这里的问题是,TypeScript 不推断具有计算属性的 object 文字中的索引签名。 最小的例子:

type KEY = 'foo' | 'bar';
let obj = { ['foo' as KEY]: 1 };

// obj is of type: { [x: string ]: number }
// and NOT the { foo: number, bar: number }
// and NOT the Record<'foo'|'bar', number>

因此,在您的示例中,您应该进行转换,并为了使其更简单,重用变量中的类型而不是重复自己:

return { [x]: result.value } as Record<typeof x, typeof result.value>;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM