繁体   English   中英

如何在 TypeScript 中定义索引签名,但值不使用联合类型?

[英]How to define the index signature in TypeScript, but the value does not use union types?

我知道我们可以像这样定义索引签名:

interface Foo {
  [index: string]: number | string
}

但我希望值的类型只能是numberstring ,而不是number | string number | string ,因为我需要将它用作这样的约束:

type Bar<T extends Foo> = ...

编辑

我终于想出了另一个解决方案(更像是一种解决方法),它实际上包括使用Mapped Types的类型扩展。 可悲的是,混合stringnumber仍然无法正常工作。 但是,您可以将类型声明为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,
};

我知道您要求扩展FooType 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接口并且只允许属性值类型为

  • Foo[keyof Foo] -> 在上面的例子中, number
  • T[keyof T] -> 在上面的例子中string (因为{ someProperty: string }

使用keyof

总之,现在bar的属性值类型只能是stringnumbernumber | 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM