typescript - 带有类型值的“打开”地图
问题描述
我想通过创建查找键来定义一种对扩展“开放”的映射,然后可以使用它来查找状态映射。类似于以下代码,但不限于 juststring
和number
as 值类型:
// 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
成为一个具体的类型,换句话说,它不应该有类型参数。
解决方案
推荐阅读
- c - 如何强制链接到旧的 libc `fcntl` 而不是 `fcntl64`?
- python - 如何在 VS Code 中创建包含 django 应用程序设置的 python 控制台?
- javascript - 我想在我的下拉列表中使用 select2。这是我的代码。但它不起作用。我需要在 .cs 文件中写一些东西吗?
- python - 如何在列表 Comperhansion 的列表末尾附加 \n
- c - windows IDE和gcc之间源代码的兼容性?
- vue.js - 无法测试 Vue 组件,因为未定义 Vue 实例
- angularjs - 如何使用angular js保存html表格的多行数据
- spring - IllegalStateException:使用 Kotlin 业务逻辑的 Spock 单元测试不能为空
- travis-ci - 未在 Travis CI 上使用 Matrix 时“未设置环境变量”
- javascript - JavaScript/ES6 属性在构造函数中设置值时不使用 setter