尝试在Typescript中使用泛型创建一个类。基本上,尝试定义输入类型(可能具有部分数据)和内部类型(将通过添加内部数据以及默认数据来处理部分数据)。
ValueType对于所有类型都是通用的,但似乎与此错误不匹配:
[ts]类型'ValueType'不能分配给'RegistryItemInputType [“ value”]'类型。 [2322]
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>
/**
* Registry Item
*/
export interface RegistryItem<ValueType> {
/**
* Registry Item Value.
*/
value: ValueType
/** Additional Item Data */
[key: string]: any,
}
export interface RegistryItemInternal<ValueType> extends RegistryItem<ValueType> {
/** Item Key */
key: string;
subscriptions: {
[key: string]: (value: ValueType) => void;
};
}
export interface RegistryItemInput<ValueType> extends Partial<Omit<RegistryItem<ValueType>, 'value'>> {
/**
* Registry Item Value.
*/
value: ValueType
}
/**
* A Base Registry
*/
export class Registry<
ValueType = any,
RegistryItemInternalType extends RegistryItemInternal<ValueType> = RegistryItemInternal<ValueType>,
RegistryItemInputType extends RegistryItemInput<ValueType> = RegistryItemInput<ValueType>
> {
/** Internal data */
protected data: Map<string, RegistryItemInternalType> = new Map();
/**
* The set() method adds or updates an element with a specified
* key and value to a Registry object.
* @param key
* @param value
*/
public set(key: string, value: ValueType) {
let item = this.getItem(key);
if (item) {
item.value = value;
} else {
item = this.createItem(key, { value });
}
this.setItem(key, item);
}
/**
* The setItem() method adds or updates an element with a specified
* key and item to a Registry object.
* @param key
* @param value
*/
public setItem(key: string, item: RegistryItemInputType) {
this.data.set(key, this.createItem(key, item));
}
/**
* The get() method returns a specified element from a Registry object.
* @param key
*/
public getItem(key: string) {
return this.data.get(key);
}
protected createItem(key: string, partial: RegistryItemInputType): RegistryItemInternalType {
return {
key,
subscriptions: {},
...(partial),
};
}
}
感谢所有帮助。