【问题标题】:Typescript index union type打字稿索引联合类型
【发布时间】:2026-01-31 03:15:01
【问题描述】:

我正在使用打字稿,并且我有一个对象,其中包含由字符串和数字引用的字段。我知道它是否仅由字符串索引,我可以使用

指定类型

var object: {[index: string]: number}

有没有办法让索引可以是字符串或数字?我试过var object: {[index: string|number]: number},但没有成功。

【问题讨论】:

  • 我不这么认为.. 我认为唯一的方法是使用: any
  • @Gustav - 你不能使用any。索引必须stringnumber

标签: javascript typescript typescript1.4


【解决方案1】:

以下在 TypeScript 操场上有效...本质上,这就是您所追求的行为(因此您不需要使用联合类型)。

var object: {[index: string]: number};

// Allowed
object[0] = 1;
object['idx'] = 2;

// Not allowed
object[1] = 'string';
object['other'] = 'string';

// Types inferred as number
var a = object[0];
var b = object['idx'];

【讨论】: