![](/img/trans.png)
[英]How to set an index signature on a class that has multiple value types in typescript?
[英]How to define the index signature in TypeScript, but the value does not use union types?
我知道我们可以像这样定义索引签名:
interface Foo {
[index: string]: number | string
}
但我希望值的类型只能是number
或string
,而不是number | string
number | string
,因为我需要将它用作这样的约束:
type Bar<T extends Foo> = ...
编辑
我终于想出了另一个解决方案(更像是一种解决方法),它实际上包括使用Mapped Types的类型扩展。 可悲的是,混合string
和number
仍然无法正常工作。 但是,您可以将类型声明为string
或任何您想要的类型,然后使用any
扩展它。
interface Foo {
[index: string]: string;
}
type Bar<T extends Foo> = { [P in keyof Foo]: Foo[keyof Foo] | T[keyof T] };
const bar: Bar<{ [index: string]: any }> = {
someProperty: "1",
anotherProperty: 2,
};
我知道您要求扩展Foo
的Type
Generic
。 我想出了一个没有那个的解决方案。 所以如果你想在这里做出妥协,你可以:
interface Foo {
[index: string]: number;
}
type Bar<T> = { [index: string]: Foo[keyof Foo] | T[keyof T] };
const bar: Bar<{ someProperty: string }> = {
someProperty: "1",
anotherProperty: 2,
};
基本上我所做的是使用你的Foo
接口并且只允许属性值类型为
使用keyof
。
总之,现在bar
的属性值类型只能是string
或number
( number | T[keyof T]
),而无需将类型硬编码为string | number
Foo
string | number
。
另一个示例boolean
:
interface Foo {
[index: string]: number;
}
type Bar<T> = { [index: string]: Foo[keyof Foo] | T[keyof T] };
const bar: Bar<{ someProperty: boolean }> = {
someProperty: "1", // error!
// ~~~~~~~~~> Type 'string' is not assignable to type 'number | boolean'. ts(2322)
anotherProperty: 2,
};
请注意,(还)不可能像这样动态地为索引签名设置类型:
interface Foo {
[index: string]: number;
}
type Bar<T> = { [index: keyof Foo]: ... };
查看此问题/建议: https : //github.com/microsoft/TypeScript/issues/1778
所以混合string
键类型和number
键类型有点困难。
interface Foo {
[index: number]: number;
}
type Bar<T> = { [index: number]: Foo[keyof Foo] | T[keyof T] };
const bar: Bar<{ 0: string }> = {
0: "1", // error!
//~> Type 'string' is not assignable to type 'number'.ts(2322)
anotherProperty: 2,
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.