typescript - 单个 TypeScript 索引类型中的多个值类型
问题描述
我想要这样的类型:
interface Foo {
foo: number;
bar: boolean;
[others: string]: string;
}
换句话说,我想foo
成为一个数字,bar
成为一个布尔值,而其他一切都是一个字符串。
但是,这样做会导致错误:
Property 'foo' of type 'number' is not assignable to 'string' index type 'string'.
我以为我会很聪明,而是这样做:
type Foo = {foo: number} & {bar: boolean} & { [others: string]: string }
但是,这会导致使用错误;例如:
const x: Foo = {
foo: 123,
bar: false,
baz: 'hello world'
};
产量:
Type '{ foo: number; bar: false; baz: string; }' is not assignable to type 'Foo'.
Type '{ foo: number; bar: false; baz: string; }' is not assignable to type '{ [others: string]: string; }'.
Property 'foo' is incompatible with index signature.
Type 'number' is not assignable to type 'string'.
如何在 TypeScript 界面中表达我想要传达的内容?
解决方案
推荐阅读
- angular - *ngIf 用于所有子路由
- react-native - react-native 上的 web3:错误:返回错误:gas 资金不足 * 价格 + 价值
- php - 如何检查请求何时发送
- c++ - 如何在派生类上使用初始化列表?
- python - 如何在 Python 中使用用户的输入调用方法
- reactjs - 一个功能组件内部可以有多个功能吗?
- excel - 将多个文件从不同文件夹复制到不同的目标文件夹
- reactjs - react.js 设置默认路由
- r - eval(substitute(x), data, parent.frame()) 中的错误:缺少参数“data”,没有默认值
- php - 如何显示和分组帖子?