typescript - 为什么打字稿通用推理优先于参数而不是赋值?
问题描述
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,只是想知道除了指定类型之外是否有解决此错误的方法。
此外,当我将道具设置为空对象时,编译器能够将泛型推断为正确的接口。
解决方案
您只需要包装类型type NoInfer<T> = [T][T extends any ? 0 : never]
即可禁用参数推断。
推荐阅读
- sql-server - 如何仅将数据从一个数据库复制到同一网络中其他服务器上的另一个数据库?
- scala - 将数据帧写入 hdfs 的 Spark 作业被中止 FileFormatWriter.scala:196
- javascript - Dropzone 客户端通过文件上传到 AWS 预签名 url 来调整大小
- android - 导航和路由颤振
- python - 循环遍历数据框(列和行)并替换数据
- git - 通过 git filter-branch 调用时反直觉的 git rm --cached 标志行为(追溯 .gitignore)
- php - Array_Filter 移除
- mysql - 我需要 Prestashop 产品的 mysql 查询(导入/导出)公式
- swift - 无法断言与屏幕边界相关的约束
- android - How to implement GridLayout in Androidx?