[英]TypeScript: What does {[key: string]: any} means as return type of a function?
I'm currently learning TypeScript and Angular.我目前正在学习 TypeScript 和 Angular。 While reading about Custom validators I came across the following piece of code from https://angular.io/guide/form-validation .在阅读自定义验证器时,我从https://angular.io/guide/form-validation 中发现了以下代码段。
export function forbiddenNameValidator(nameRe: RegExp): ValidatorFn {
return (control: AbstractControl): {[key: string]: any} | null => {
const forbidden = nameRe.test(control.value);
return forbidden ? {'forbiddenName': {value: control.value}} : null;
};
}
I don't really understand what return type of the inner function ie {[key: string]: any}
means?我真的不明白内部函数的返回类型是什么,即{[key: string]: any}
是什么意思? I understand key:string
part, ie Object's key is of type string but what exactly {[key: string]: any}
means?我理解key:string
部分,即 Object 的 key 是 string 类型,但究竟{[key: string]: any}
是什么意思?
It means the function returns an object that you can index into with any string value;这意味着该函数返回一个对象,您可以使用任何字符串值对其进行索引; the property's result value type is any
meaning it can be, well, anything.属性的结果值类型是any
含义,它可以是任何东西。 (The | null
means it can also return null
instead of returning an actual object.) ( | null
意味着它也可以返回null
而不是返回实际对象。)
Object −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−v−−−−−−−−−−−−−−−−−−v {[key: string]: any} Key of all properties is any string −−−−−^^^^^^^^^^^^^ ^^^−−−−− type of all properties is `any`
It's a very broad type.这是一个非常广泛的类型。
More in the documentation of index signatures .更多在索引签名的文档中。
It returns an object, like它返回一个对象,比如
{
"name": "John"
}
or或者
{
"length": 5
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.