首页 > 解决方案 > 为什么打字稿通用推理优先于参数而不是赋值?

问题描述

Typescript 泛型推断优先于参数而不是赋值。由于它优先考虑参数,因此任何 param props 都会自动转换为 type unknown,即使我将它分配给一个变量,其类型 param 设置为对象接口。

interface Person {
  name: string;
  age: number;
  id: string;
}

interface Client {
  person: Person;
}

class FormField {  }

class FormFieldGroup<T> {
  constructor(private props: { category: string, questions: FormRelation<Required<T>> }) {}
}

type Primitives = string | number | symbol | bigint | undefined | null;

type FormRelation<T> = {
  [K in keyof T]: T[K] extends Primitives ? FormField : FormFieldGroup<T[K]>;
}

abstract class CRUDComponent<D> {
  public abstract clientQuestions: FormRelation<D>
}

class ClientComponent extends CRUDComponent<Client> {
  public clientQuestions: FormRelation<Client> = {
    person: new FormFieldGroup({
      category: "Client",
      questions: {
        name: new FormField(),
        age: new FormField(),
        id: new FormField(),
      }
    })
  }
}

VScode: Cannot assign FormQuestionGroup<{name: unknown, age: unknown, id: unknown}> to FormQuestionGroup<Person>.

在 Java 中,菱形运算符会自动推断类型以匹配赋值类型参数。但是,为了便于阅读,Typescript 不包含菱形运算符。我正在使用 typescript 3.7,只是想知道除了指定类型之外是否有解决此错误的方法。

此外,当我将道具设置为空对象时,编译器能够将泛型推断为正确的接口。

打字稿游乐场

标签: typescriptgenericstypescript-typingstype-inferencetypescript-generics

解决方案


您只需要包装类型type NoInfer<T> = [T][T extends any ? 0 : never]即可禁用参数推断。


推荐阅读