简体   繁体   English

在TypeScript中,如何指定对象中值的类型?

[英]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.

相关问题 如何将联合类型指定为对象键 Typescript - How to specify union types as object keys Typescript 如何在typescript定义中指定松散类型的对象文字? - How can I specify loosely typed object literal in typescript definition? 如何在 TypeScript 中指定类型化的对象文字? - How can I specify a typed object literal in TypeScript? 将 object 传递给 function 时,如何指定 TypeScript 类型? - How can I specify a TypeScript type when passing an object into a function? 在 TypeScript 中,我可以指定 object 字段的类型,同时仍能推断出文字键类型吗? - In TypeScript, can I specify the type of object fields while still getting the literal key types inferred? 在 Typescript 中,如何指定可以返回多种类型的函数的返回类型? - In Typescript, how can I specify the return type of a function that can return multiple types? 如何在Typescript中定义对象变量的类型? - How can I define the types of an object variable in Typescript? 如何将我的 nextjs typescript(接口/类型)与 nodejs 服务器 typescript 模型(接口/类型)一起保存? - How I can keep my nextjs typescript (interfaces / types) with nodejs server typescript models (interfaces / types)? 如何使用 TypeScript 保护我的域驱动类型? - How can I secure my domain-driven types with TypeScript? 如何在 TypeScript 中指定隐含类型 - How to specify implied types in TypeScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM