[英]In TypeScript, how can I specify the types of the values in my object?
For example, suppose I have: 例如,假设我有:
export function trade(positions: object) {
...
}
but instead of just specifying that 'positions' is an object, I want to specify that it is an object with values that must be Strings. 但是,我不仅要指定“ positions”是一个对象,还要指定它是一个值必须为Strings的对象。
What is the syntax for that? 它的语法是什么?
Edit: 编辑:
To tighten the example, suppose I just want keys and values to all be Strings. 收紧示例,假设我只希望键和值都为字符串。 Is there a syntax for that?
有语法吗?
If you want to share the object is as wide as "has string keys, and string values" you can use an index type: 如果要共享对象的宽度与“具有字符串键和字符串值”一样宽,则可以使用索引类型:
export function trade(positions: {[key: string]: string;}) {
// ...
}
If you want to make it more specific, it may be time to create an interface - even if everything is optional - as it will give you more design-time help when creating a positions object. 如果要使其更加具体,则可能是时候创建一个接口了-即使所有内容都是可选的-因为在创建positions对象时它将为您提供更多的设计时帮助。
interface Positions {
x?: string;
y?: string;
z?: string;
t?: string;
}
This doesn't force any of the items to be present, but you'll get good auto-completion. 这不会强制显示任何项目,但是您会获得良好的自动完成功能。 If the members are required, you can make them non-optional.
如果需要成员,则可以使它们成为非可选。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.