gpt4 book ai didi

javascript - 当类型是 map 的任何成员时提高 Typescript 速度?

转载 作者:行者123 更新时间:2023-12-04 14:02:33 25 4
gpt4 key购买 nike

例如,我有这些类型:

class User extends Entity {}

class Post extends Entity {}

type Entities = {
user: User,
post: Post,
// potentially hundreds more
};

type EntityType = 'user' | 'post' | ...;

当我在泛型中使用 EntitiesEntityType 时,它会显着降低 Typescript 的速度。仅在 VS Code 中显示类型信息就需要几分钟。我有通用功能,例如:

function getEntityFromCache<T extends EntityType>(type: T, id: number): Entities[T] | null | undefined;

function getEntity<T extends EntityType>(type: T, id: number): Entities[T] | null {
const cachedEntity = getEntityFromCache(type, id);
if (cachedEntity !== undefined) {
return cachedEntity;
}
...
}

我对为什么这很慢的理解是因为 Entities[T]Entities 所有值的联合,即 User |发表 | ...。 TS 不能很好地处理工会。要检查 cached 的返回类型是否正确,TS 必须遍历 T 的每个可能值。 IE。如果 T = 'user',验证 cachedEntityEntities['user'];如果 T = 'post',验证 cachedEntityEntities['post'];等等。这很慢,因为每次我有泛型时,TS 都必须检查联合的每个值。

此外,TS 不只是比较泛型值('user' === 'user''post' === 'post'),而是比较整个实体(User === UserPost === Post)。这使情况变得更糟,因为实体很复杂。

有哪些方法可以加快速度?以下是我的一些想法:

  1. 从中间函数中删除泛型并使它们返回基本实体类型,然后对其进行类型转换。例如。 函数 getEntityFromCache(类型:T,id:数字):实体 |空 |未定义;

  2. 以某种方式让 TS 比较实体类型字符串而不是比较整个实体。

最佳答案

根据 TypeScript 维基页面 Preferring Base Types Over Unions值得使用子类型,而不是联合。

However, they also come with a cost. Every time an argument is passed to printSchedule, it has to be compared to each element of the union. For a two-element union, this is trivial and inexpensive. However, if your union has more than a dozen elements, it can cause real problems in compilation speed. For instance, to eliminate redundant members from a union, the elements have to be compared pairwise, which is quadratic. This sort of check might occur when intersecting large unions, where intersecting over each union member can result in enormous types that then need to be reduced. One way to avoid this is to use subtypes, rather than unions.

文档中的简化示例:


interface A {
char: 'a' | 'b' | 'c' | 'd' | 'e';
}

interface B extends A {
char: 'a' | 'b';
}

interface C extends A {
char: 'd' | 'e';
}


declare function char(schedule: A): void;

关于javascript - 当类型是 map 的任何成员时提高 Typescript 速度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69551641/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com