我无法理解 typescript 中的以下类型。 obj 值的示例将非常有帮助。
obj: { [name: string]: string | string[]; };
我实际上是想了解 Angular 中 HttpClient 的 post 方法中选项对象的 headers 属性的类型:
post(url: string, body: any | null, options: {
headers?: HttpHeaders | {
[header: string]: string | string[];
};
...
}
最佳答案
让我们使用以下 Typescript 规则逐步分解它
类型定义之间带有竖线的类型定义称为 union type这意味着它可以是任何已定义的类型。
let foo: string | number = 0; // foo must be a string or a number
foo = "a string";
返回类型可以是对象。在这种情况下,您可以通过键入键的名称和类型来定义键。
const obj: {
foo: string,
bar: number
} = {foo: "a string", bar: 42 }
const err: {
foo: string,
bar: number
} = {foo: "a string", bar: "another string" } // this would not work, because we defined bar as a number
我们也使用联合类型来定义类型
let obj: {
foo: string,
bar: number | string
} = {foo: "a string", bar: "another string" } // this works because bar can be a number OR a string
对象键后面的问号表示它是可选的。
const foo: {
foo?: string
} = {} // is valid
const bar: {
foo?: string
} = { foo: "a string" } // is also valid
const baz: {
foo?: string
} = {bar: "a string"} // invalid because bar is no property of type {foo?: string}
{[key: string]: string}
类型表示允许任何键,只要它可以转换为字符串,
const foo: {
[key: string]: string
} = {foo:"a string", bar: "another string", baz: "yet another string"} // is all valid
在上面写的例子中,只要类型是字符串,每个键都是有效的。
const bar: {
[key: string]: string
} = {foo:"a string", bar: "another string", baz: 42} // is invalid baz is not of type string
在此示例中,对象无效,因为 baz 不是 string
类型
联合类型也可以工作
const baz: {
[key: string]: string | number
} = {foo:"a string", bar: "another string", baz: 42} // is valid
所以根据上面的规则我们可以分解这个方法
该方法称为 post,它接受三个参数:
- url - 这是
string
类型(在此方法中,它是进行 POST 调用的 url) - body - 这是类型
any
OR 类型null
(在这个方法中它是 body电话后) - 选项:这个选项可能看起来令人困惑,所以让我们分解一下:
options 必须是一个 object
,它有一个名为 headers 的可选键(它是可选的,因为它以问号结尾)。 key 必须命名为 headers,不能命名为其他名称。不能插入其他键和值!
headers
必须是 HttpHeaders 类型(一个由 angular 生成的类)或一个 object
可以将键转换为字符串 由于几乎所有内容都可以转换为字符串,因此几乎所有内容都可以成为关键。该值必须是字符串或字符串数组。
希望对你有帮助
关于javascript - Angular HttpClient post 方法参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52862565/