TypeScript-泛型约束能否提供;“允许”;类型?

TypeScript-泛型约束能否提供;“允许”;类型?,typescript,generics,generic-constraints,Typescript,Generics,Generic Constraints,给定以下代码 type Indexable<TKey, TValue> = { [index: TKey]: TValue } type Indexable={[index:TKey]:TValue} 这会产生以下错误: 索引签名参数类型必须为“字符串”或“数字” 是否有方法将TKey约束为“字符串”或“数字”?您可以将TKey约束为从字符串或数字派生(使用扩展名),但这不会满足编译器的要求索引必须是数字或字符串,而不是泛型类型或任何其他类型。这在中有说明,您不能使用TKey作为

给定以下代码

type Indexable<TKey, TValue> = { [index: TKey]: TValue }
type Indexable={[index:TKey]:TValue}
这会产生以下错误:

索引签名参数类型必须为“字符串”或“数字”


是否有方法将TKey约束为“字符串”或“数字”?

您可以将TKey约束为从字符串或数字派生(使用扩展名),但这不会满足编译器的要求<代码>索引必须是数字或字符串,而不是泛型类型或任何其他类型。这在

中有说明,您不能使用
TKey
作为索引签名中的类型,即使它是

如果您知道
TKey
正是
string
number
,您可以直接使用它,而不在您的类型中指定
TKey

type StringIndexable<TValue> = { [index: string]: TValue }
type NumberIndexable<TValue> = { [index: number]: TValue }
编辑:注意添加了TS2.9。我们将使用
keyofany
来表示“您的TypeScript版本认为是有效的键类型”。回到答案的其余部分:


如果要允许
TKey
比任何的
key更具体,这意味着只允许使用某些键,可以使用:

如果您不想将键限制为特定的文本或文本的并集,您仍然可以使用
string
作为
TKey

type NumNames = 'zero' | 'one' | 'two';
const nums: Indexable<NumNames, number> = { zero: 0, one: 1, two: 2 };

type NumNumerals = '0' | '1' | '2';
const numerals: Indexable<NumNumerals, number> = {0: 0, 1: 1, 2: 2};
const anyNums: Indexable<string, number> = { uno: 1, zwei: 2, trois: 3 };
const anyNums:Indexable={uno:1,zwei:2,trois:3};

事实上,
Indexable
的这个定义非常有用,它已经存在于:

type NumNames='zero'|'one'|'two';
常量nums:Record={0:0,1:1,2:2};
因此,我建议您出于这些目的使用
Record
,因为它是标准的,其他阅读您的代码的TypeScript开发人员可能更熟悉它



希望有帮助;祝你好运

顶级解决方案:
StringIndexable
NumberIndexable
正是我最终要做的!非常全面,谢谢。
type NumNames = 'zero' | 'one' | 'two';
const nums: Indexable<NumNames, number> = { zero: 0, one: 1, two: 2 };

type NumNumerals = '0' | '1' | '2';
const numerals: Indexable<NumNumerals, number> = {0: 0, 1: 1, 2: 2};
const anyNums: Indexable<string, number> = { uno: 1, zwei: 2, trois: 3 };
type NumNames = 'zero' | 'one' | 'two';
const nums: Record<NumNames, number> = { zero: 0, one: 1, two: 2 };