首页 > 解决方案 > 带有类型值的“打开”地图

问题描述

我想通过创建查找键来定义一种对扩展“开放”的映射,然后可以使用它来查找状态映射。类似于以下代码,但不限于 juststringnumberas 值类型:

// Map and lookup key types
export type LookupKey<T> = symbol & { value: T };
export type State = {
  [key: LookupKey<string>]: (typeof key)["value"] | undefined;
  [key: LookupKey<number>]: (typeof key)["value"] | undefined;
}

// Clients can define their "lookup keys"
export const stringSymbol = Symbol('string') as LookupKey<string>;
export const numberSymbol = Symbol('number') as LookupKey<number>;

// ...and then use in a type-safe manner (sort of)
export function whatever(state: State) {
  // fine
  const stringValue: string | undefined = state[stringSymbol];
  state[stringSymbol] = "hello";
  // not fine -- types mismatch!
  const notAStringValue: number | undefined = state[stringSymbol];
  state[stringSymbol] = 123; 
}

是否可以在 TypeScript 中编写这样的类型签名?我想State成为一个具体的类型,换句话说,它不应该有类型参数。

标签: typescripttypessymbols

解决方案


推荐阅读