You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript能否构建值类型由键推断的字典并实现指定行为?

在TypeScript中构建值类型由键推断的字典

当然可以实现这种需求,用TypeScript的映射类型就能轻松搞定,下面是具体的实现步骤:

首先修正你代码里的语法错误(接口未闭合),先定义好基础类型:

interface Foo {
  kind: 'foo',
  info: string,
  someProperty: string
}

interface Bar {
  kind: 'bar',
  info: string,
  otherProperty: string
}

步骤1:创建键与类型的映射表

先定义一个类型,把你需要的键('foo'、'bar')和对应的目标类型(Foo、Bar)绑定起来:

type KindToType = {
  foo: Foo;
  bar: Bar;
};

步骤2:构建带类型推断的字典类型

利用TypeScript的映射类型,遍历KindToType的所有键,为每个键定义对应的函数类型(参数类型自动从键映射而来):

type Dictionary = {
  [K in keyof KindToType]: (item: KindToType[K]) => void;
};

步骤3:定义符合要求的字典实例

现在你可以创建字典了,TypeScript会自动推断每个函数的参数类型,并且严格校验类型匹配:

const a: Dictionary = {
  'foo': (item) => {
    // item自动推断为Foo类型,可直接访问someProperty
    console.log(item.someProperty);
  },
  'bar': (item) => {
    // item自动推断为Bar类型,可直接访问otherProperty
    console.log(item.otherProperty);
  }
};

如果尝试给某个键绑定参数类型不匹配的函数(比如给'foo'绑定接收Bar类型的函数),TypeScript会立即抛出类型错误,完全满足你的类型安全需求。

内容的提问来源于stack exchange,提问作者Chabbey François

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 02:25:12