为什么对象上的数组访问运算符 ([]) 不是错误?
Why is array access operator ([]) on objects not an error?
在重构我的代码时,我偶然发现了我不理解的 TypeScript 编译器的奇怪行为。
interface IPoint {
x: number;
y: number;
}
let a: IPoint = { x: 5, y: 10 };
let b = a[0];
console.log(b);
编译此代码时,我预计编译器会抛出错误,因为访问 a
的键绝对不存在(在编译时)。
这是为什么?是否还有一个 TSLint 选项我不知道标记 []
在对象上用作 error/warning?
提前致以最诚挚的问候和感谢
使用默认的编译器设置,typescript 将允许使用任何键对任何对象进行索引操作(结果将是 any
类型)。要使其成为错误,请使用 noImplicitAny
编译器选项。
我强烈建议打开 --strict
compiler option。这个选项打开了一堆额外的检查,这对于捕获错误是非常宝贵的。在您的情况下,您想要的特定检查是通过 --noImplicitAny
选项完成的:
--noImplicitAny
: Raise error on expressions and declarations with an implied any
type.
如果打开它,您会看到以下错误:
let b = a[0]; // error!
// Element implicitly has an 'any' type because type 'IPoint' has no index signature.
您可能会发现,如果您打开 --strict
模式,会出现许多其他错误。这很烦人,但通常这些都是您应该处理的好错误,即使出现误报,处理这些错误也会让您的代码变得更好。
希望对您有所帮助;祝你好运!
在JavaScript中,[]
不只是一个数组索引运算符,它也是一个property accessor,也就是说可以用于访问对象的属性,例如
const animal = {
legCount: 4
};
console.log(animal.legCount); // 4
console.log(animal['legCount']); // 4
作为 discussed here,TypeScript 隐式地为所有索引提供类型 any
:
JavaScript allows to index into any object. TypeScript compiler can not statically know type checked all these, e.g. var name = getName(); x[name];
. so it gives it the type any
.
要添加某种级别的保护,您可以尝试添加索引签名并指定预期的类型。
interface IPoint {
x: number;
y: number;
[key: string]: number; // This object will contain only number properties.
}
在重构我的代码时,我偶然发现了我不理解的 TypeScript 编译器的奇怪行为。
interface IPoint {
x: number;
y: number;
}
let a: IPoint = { x: 5, y: 10 };
let b = a[0];
console.log(b);
编译此代码时,我预计编译器会抛出错误,因为访问 a
的键绝对不存在(在编译时)。
这是为什么?是否还有一个 TSLint 选项我不知道标记 []
在对象上用作 error/warning?
提前致以最诚挚的问候和感谢
使用默认的编译器设置,typescript 将允许使用任何键对任何对象进行索引操作(结果将是 any
类型)。要使其成为错误,请使用 noImplicitAny
编译器选项。
我强烈建议打开 --strict
compiler option。这个选项打开了一堆额外的检查,这对于捕获错误是非常宝贵的。在您的情况下,您想要的特定检查是通过 --noImplicitAny
选项完成的:
--noImplicitAny
: Raise error on expressions and declarations with an impliedany
type.
如果打开它,您会看到以下错误:
let b = a[0]; // error!
// Element implicitly has an 'any' type because type 'IPoint' has no index signature.
您可能会发现,如果您打开 --strict
模式,会出现许多其他错误。这很烦人,但通常这些都是您应该处理的好错误,即使出现误报,处理这些错误也会让您的代码变得更好。
希望对您有所帮助;祝你好运!
在JavaScript中,[]
不只是一个数组索引运算符,它也是一个property accessor,也就是说可以用于访问对象的属性,例如
const animal = {
legCount: 4
};
console.log(animal.legCount); // 4
console.log(animal['legCount']); // 4
作为 discussed here,TypeScript 隐式地为所有索引提供类型 any
:
JavaScript allows to index into any object. TypeScript compiler can not statically know type checked all these, e.g.
var name = getName(); x[name];
. so it gives it the typeany
.
要添加某种级别的保护,您可以尝试添加索引签名并指定预期的类型。
interface IPoint {
x: number;
y: number;
[key: string]: number; // This object will contain only number properties.
}