TypeScript对象和键推断

问题描述 投票:0回答:1

我试图构建一个通用组件,它接受三个参数:1。来自MobX商店的可观察对象。 2.连接到同一商店的“onChange”回调。 3.并作为最后一个键 - 一个路径字符串,它是参数1的键之一

此组件存在的原因是允许轻松使用商店,例如:

<StoreInput path="email" />

该组件工作正常,但现在我尝试强制将'path'类型作为对象键之一(以及onChange参数的键) - 但到目前为止,我从TypeScript中获得了编译器错误。

任何帮助将不胜感激。

type objectType = { [key: string]: string };


type changeType<O> = {
  [x in keyof O]: string
}

const createStoreInput = <T extends objectType>(objecyComputed: IComputedValue<T>) => (onChange: (change: changeType<T>) => void) =>
  observer(({ path }: { path: keyof T }) => {
    const currentValue = objecyComputed.get()[path];
    return (
      <InputRow
        value={currentValue}
        onChange={newValue => {
          const change = { [path]: newValue };
          onChange(change);
        }}
      />
    );
  });

TypeScript错误:类型'{[x:string]的参数:string; }'不能赋值给'changeType'类型的参数。 TS2345

50 |         onChange={newValue => {
51 |           const change = { [path]: newValue };

52 |的onChange(变化); | ^ 53 | 54 | /> 55 | );

reactjs typescript mobx
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.