简体   繁体   English

如何在 TypeScript 严格模式下使用方括号表示法访问对象的属性

[英]How to access a property of an object using the bracket notation in TypeScript strict mode

The following TypeScript sample code shows an error Element implicitly has an 'any' type because type '{one: number; two: number;}' has no index signature以下 TypeScript 示例代码显示了一个错误Element implicitly has an 'any' type because type '{one: number; two: number;}' has no index signature Element implicitly has an 'any' type because type '{one: number; two: number;}' has no index signature in the line const one = obj[prop];二:number;}' 在const one = obj[prop];Element implicitly has an 'any' type because type '{one: number; two: number;}' has no index signature in strict mode.在严格模式下。

The compiler allows the line const two = obj[propName];编译器允许行const two = obj[propName]; , so I cannot understand why the error is shown or how to generally speaking access a property of an object using the bracket notation. ,所以我不明白为什么会显示错误,或者一般来说如何使用方括号表示法访问对象的属性。

const obj = { one: 1, two: 2 };

const props = { one: 'one', two: 'two' };

// it is not possible add or change any properties in the props object 
props.zero = 'zero';
props.one = 1;

// prop has the type string
const prop = props.one;

// using the bracket notation fails with the following error message:
// Element implicitly has an 'any' type because type '{one: number; two: number;}' has no index signature.
// const prop: string
const one = obj[prop];

// this works because propName is of type 'two'
const propName = 'two';
const two = obj[propName];

Element implicitly has an 'any' type because type '{one: number;元素隐含地具有“任何”类型,因为类型 '{one: number; two: number;}' has no index signature二:number;}' 没有索引签名

Your object has no index signature, it has two named properties.您的对象没有索引签名,它有两个命名属性。

The compiler allows the line const two = obj['two'];编译器允许行 const two = obj['two'];

It allows the names of your properties, that's why obj['two'] and obj['one'] will work.它允许你的属性名称,这就是为什么 obj['two'] 和 obj['one'] 可以工作的原因。

and the const prop is a string, so I cannot understand why the error is shown并且 const 道具是一个字符串,所以我不明白为什么会显示错误

Because a string can have much more values that just 'one' or 'two' and so the compiler cannot ensure, your object[myString] call will work.因为一个字符串可以有更多的值,只有“一”或“二”,所以编译器不能确保,你的object[myString]调用将起作用。 It's only valid for two defined string values.它仅对两个定义的字符串值有效。

how to generally speaking access a property of an object using the bracket notation.一般而言,如何使用方括号表示法访问对象的属性。

This would work:这会起作用:

 const prop: 'one' | 'two' = 'one';
 const test = obj[prop]

You say: prop has value 'one' or 'two' and so the compiler knows your obj[prop] will always be valid.你说: prop 的值是“一”或“二”,所以编译器知道你的 obj[prop] 总是有效的。

or或者

 class Example {
   one: string;
   two: string;
 }
 const prop: keyof Example = 'one';
 const test = obj[prop];

Here keyof(ClassName) tells the compiler, that your prop var will have an existing property name of Example .这里keyof(ClassName)告诉编译器,您的 prop var 将具有Example的现有属性名称。

The above examples assume, that you have an object where only the properties named 'one' and 'two' are valid.上面的示例假设您有一个对象,其中只有名为“一”和“二”的属性有效。 If you want to use your object in a "dictionary style", tell typescript about that and add an index signature:如果您想以“字典样式”使用您的对象,请告诉 typescript 并添加索引签名:

 const obj: {[key:string]: string;} = { one: 'one' };
 const text = obj[myString];

Now obj allows every string values as key.现在 obj 允许每个字符串值作为键。

Particularly I'm fan of strong type, but const obj: any should be ok.特别是我是强类型的粉丝,但const obj: any应该没问题。


interface test { 
    one: string;
    two: string;
}

const props: test = { one: 'one', two: 'two' }; // {one: string, two: string}
const obj: any = {one: 1, two: 2}; // {one: number, two: number}


const two = obj['two']; // number

const prop = props.one; // string

const one = obj[prop];

Enum Solution枚举解决方案

enum numbers {
    one = 1,
    two = 2
}

const oneStr = numbers[numbers.one];
const one = numbers[oneStr];

As has been mentioned, the inferred type of props is {one: string, two: string} .如前所述, props的推断类型是{one: string, two: string} This means props.one could be any string (even though we see it is "one"), so when you write obj[props.one] what you're really accessing is obj[string] which may not be allowed.这意味着props.one可以是任何字符串(即使我们看到它是“one”),所以当您编写obj[props.one]时,您真正访问的是obj[string] ,这可能是不允许的。

If you made your props an explicit type, you could get around it: type Props = {one: "one", two: "two"} , and then use it: const props: Props = {one: "one", two: "two"}如果你将 props 设为显式类型,你可以绕过它: type Props = {one: "one", two: "two"} ,然后使用它: const props: Props = {one: "one", two: "two"}

This way the type of props is not inferred, and the explicit type of the values is "one" or "two".这种方式不会推断props的类型,并且值的显式类型是“一”或“二”。

But that's annoying to write when what you really want to say is that props is these exact values.但是当你真正想说的是props是这些确切的值时,这很烦人。 You can tell the compiler not to be clever about the type it infers and use the exact values you specified with as const :您可以告诉编译器不要对它推断的类型很聪明,并使用您指定的确切值as const

const obj = { one: 1, two: 2 };
const props = { one: 'one', two: 'two' } as const;

const prop = props.one;

const one = obj[prop];

Now the compiler knows that prop has the exact value "one" instead of any string .现在编译器知道prop具有确切的值 "one" 而不是任何string So it is allowed.所以是允许的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 TypeScript 中括号符号中的变量访问 object 属性 - Access object property using variable in bracket notation in TypeScript Typescript:括号表示法属性访问 - Typescript: bracket notation property access 如何通过Typescript中的点表示法或括号表示法访问object? - How to access object by dot notation or bracket notation in Typescript? Typescript:使用方括号表示法和变量访问 object 属性 - Typescript: access an object property with square bracket notation and variable 为什么 Typescript 不允许我使用括号表示法访问 object 的属性? - Why won't Typescript let me access the property of an object using bracket notation? Typescript 使用括号表示法访问 object 的可选属性 - Typescript using bracket notation to access optional properties of an object 使用带有变量的括号表示法来访问 object 属性返回未定义 - Using bracket notation with a variable to access object property returns undefined 在Typescript严格模式下使用表达式作为对象的属性名时,如何检查未定义? - How do you check for undefined when using an expression as the property name of object in Typescript strict mode? 如何使用括号表示法检查打字稿中的无效性 - How to check nullity in typescript using Bracket notation 尝试使用方括号表示法访问对象属性时出现Typescript错误TS1003 - Typescript Error TS1003 when attempting to access object properties using bracket notation
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM