gpt4 book ai didi

javascript - 将 id 分配给 id 属性名称可配置的通用类型?

转载 作者:行者123 更新时间:2023-11-30 20:10:39 25 4
gpt4 key购买 nike

我有一个通用类型E。它是一个实体实例,如 CustomerProductTodo 等。它有两个可配置字段 idguid,但是它们不一定是这样命名的。这两个属性的名称是可配置的。

这是一个实体的例子:

class Todo {
id: string;
gid: string;
title: string;
completed: boolean;
}

为了配置属性名称,使用了这样的配置类:

    /**
* Store configuration.
*/
export class StoreConfig {
idKey?:string ='id';
guidKey?:string ='gid';
}

StoreConfig 用于确定生成的 ID 分配给类型 E 的实例的属性名称。所以我们有这样的方法:

/**
* Post (Add a new) element to the store.
* @param e
*/
post(e: E) {
const guid: string = v1();
e[this.config.guid] = guid;
this.entries[guid] = e;

typescript 抛出:

[ts] Element implicitly has an 'any' type because type '{}' has no index signature (property) EStore.config: StoreConfig

有办法解决这个问题吗?这是一个小技巧,因为 E 类型有两个属性全名是可配置的...?

此外,该类本质上有两个索引签名。一个用于 id 属性(还未命名/可配置),一个用于 guid 属性(还未命名/可配置)...

如果我这样做:

    (<any>e)[this.config.guidKey] = guid;

Typescript 没有提示,但我想知道是否有更优雅的方式来声明它?

最佳答案

这两个属性的名称需要类型参数。 (好吧,由于属性具有相同的类型 string,您可以将单个类型参数与联合类型一起使用,但那是 IMO 的 hack。)然后您可以使用映射类型来声明实际属性.

interface StoreConfig<I extends string, G extends string> {
idKey: I;
guidKey: G;
}

type EntityBase<I extends string, G extends string> =
// TODO: In TypeScript 3.1, change to the following for elegance:
//{[P in I]: string} & {[P in G]: string}
{[P in I | G]: string};

class Store<I extends string, G extends string, E extends EntityBase<I, G>> {
constructor(private config: StoreConfig<I, G>) {}

entries: {[guid: string]: E};

post(e: E) {
const guid: string = v1();
e[this.config.guidKey] = guid;
this.entries[guid] = e;
}
}

// https://github.com/Microsoft/TypeScript/issues/10571 will make this nicer.
new Store<"id", "gid", Todo>({idKey: "id", guidKey: "gid"});

关于javascript - 将 id 分配给 id 属性名称可配置的通用类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52451522/

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