【问题标题】:Record<string, unknown> is missing the properties of CustomTypeRecord<string, unknown> 缺少 CustomType 的属性
【发布时间】:2021-12-04 02:28:03
【问题描述】:

我的项目中有这个设置:

interface GenericFn<TInput extends Record<string, unknown>, TOutput extends Record<string, unknown>> {
    (input: TInput): TOutput;
}

type AddNumberInput = {
    number1: number;
    number2: number;
};

type AddNumberOutput = {
    sum: number;
};

每当我尝试这样做时:

const fn1: GenericFn<AddNumberInput, AddNumberOutput> = (input) => { 
    return { sum: input.number1 + input.number2 }; 
};

const fn2: GenericFn<Record<string, unknown>, Record<string, unknown>> = fn1; // ERROR 2322

我收到此错误:

Type 'GenericFn<AddNumberInput, AddNumberOutput>' is not assignable to type 'GenericFn<Record<string, unknown>, Record<string, unknown>[]>'.

  Type 'Record<string, unknown>' is missing the following properties from type 'AddNumberInput': number1, number2 ts(2322)

但是,我已经确认AddNumberInputAddNumberOutput 可以分配给类型Record&lt;string, unknown&gt;

const type1: AddNumberInput = {
    number1: 1,
    number2: 2
};
const type2: AddNumberOutput = {
    sum: 3
};

let genericType: Record<string, unknown>;
genericType = type1; // No errors
genericType = type2; // No errors

应该怎么做呢?我想将每个通用函数存储在一个对象集合中,如下所示:

const fns: {
    [id: string]: GenericFn<Record<string, unknown>, Record<string, unknown>>
} = {};

fns["fn1"] = fn1; // ERROR 2322

但由于此错误,我似乎无法存储它们。应该如何实施呢?谢谢!

编辑:根据要求,这是我的 tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react"
  },
  "include": [
    "src"
  ]
}

如果我没记错的话,这是 Create-React-App Typescript 模板附带的 tsconfig.json

【问题讨论】:

  • 嘿,在上面的代码上运行tsc 不会给我任何错误。您能否提供您的tsconfig.json 文件?
  • @h-sifat 我已更新问题以包含我的tsconfig.json 文件。
  • 您不需要预先定义返回类型。请参阅此示例:https://tsplay.dev/mLRpZw
  • 我试着环顾四周,真的找不到任何可靠的东西。如果您想要快速简单的东西,请执行以下操作:fns["fn1"] = fn1 as any;

标签: typescript typescript-generics


【解决方案1】:

我发现可以通过在tsconfig.json 中将strictFunctionTypes 设置为false 来解决此问题。但是,我不确定在我的应用程序开发过程中关闭此设置会产生什么后果。也许我必须寻找一个更适合我需要的替代方案。

【讨论】:

  • 如果类型安全对您很重要,请不要这样做。
  • 我绝对同意,这就是为什么我犹豫是否将其作为这个问题的最终答案。这仍然是一个可能的解决方案,但我也在寻找其他解决方案。
猜你喜欢
  • 1970-01-01
  • 2022-09-23
  • 2018-03-03
  • 2021-10-02
  • 2021-03-13
  • 2021-11-26
  • 1970-01-01
  • 2020-12-16
  • 2019-12-04
相关资源
最近更新 更多