English 中文(简体)
描述为何造成这一错误? 通用指数类
原标题:Why does Typescript give this error? Generic indexed type

一、这种通用类型:

type MapToFunctions<T> = {
  [K in keyof T]?: (x: T[K]) => void;
};

在本案中,它进行罚款:

type T1 = { a: string };

const fnmap1: MapToFunctions<T1> = {
  a: (x: string) => {
    console.log(x);
  },
}

我甚至可以排除<代码>x的类型,而原型则可以正确地推断出它有线。

但是,如果在作为参数使用的类型上添加一个指数签名,那么它就不再工作:

type T2 = {
  a: string;
  [key: string]: unknown;
}

const fnmap2: MapToFunctions<T2> = {
  a: (x: string) => {
    console.log(x);
  },
}

我发现这一错误:

Type  { a: (x: string) => void; }  is not assignable to type  MapToFunctions<T2> .
  Property  a  is incompatible with index signature.
    Type  (x: string) => void  is not assignable to type  (x: unknown) => void .
      Types of parameters  x  and  x  are incompatible.
        Type  unknown  is not assignable to type  string .ts(2322)

Why does this error happen? It seems pretty obvious that property a should have type (x: string) => void. In fact, TypeScript seems to agree; if I leave out the type annotation for argument x, TypeScript infers that it is a string... but then still gives the same error!

问题回答

在阐述这一问题时,我认为我略为夸张了这个问题,尽管我仍然赞赏作出更明确和(或)更直观的答复。

Type MapToFunctions<T2> is equivalent to:

{
  a: (x: string) => void;
  [key: string]: (x: unknown) => void;
}

这实际上不属于法律范畴。

添加索引签字<代码>[关键:指示]: 物体类型系指“所有other string-keyed property都有类型”。 这意味着“allstring-keyed property have打字型”。 为此,所有明确申报的财产类型都必须符合<代码>的类型。 类型

添加<代码>[钥匙:string]:不详,因为每一种类型都是un known的亚类;即。 每一条<代码>均不为人所知。 类型。 但在上述类型中,<代码>(x:string) => 空白不是(x:不详) => 真空 (事实上它环绕)。 因此,这种类型是自订的。

我发现这个问题非常好。 我的新定义是:

type MapToFunctions<T> = {
  [K in keyof T as string extends K ? never : K]?: (x: T[K]) => void;
};

索引签字中的额外操作意味着,只有明文申报的类型<代码>T的特性才被结转到相应的类型;任何<代码>[关键:指示]: 类型特性被移除。 http://code>MapToFunctions<T2>目前相当于

{
  a: (x: string) => void;
}

不存在矛盾。 如果我实际上需要这些指数化的财产,我想会有问题,但我没有。 (当然,与我的实际法典相比,这非常简化。)

完全理解<代码>MapToFunctions的新定义,留待读者使用。





相关问题
store data in memory with nestjs

I am trying to persist some data in my nestjs server so I can then use that data in my client app through http requests. I have created a products.service.ts file with the function getAllData() that ...

React Hook Form Error on custom Input component

I am having a problem when I use react hook form + zod in my application, in short the inputs never change value and I get the following error in the console: Warning: Function components cannot be ...

Updatable promises using proxy in JavaScript

EDIT: I ve updated this question, and the old question is moved here. A POC can be found on this jsfiddle or the snippet below GOAL: The goal here is to make or rather simulate a promise that can be ...

热门标签