我有以下代码片段:
...
const fd = FroniusMeter.getInstance(req.query.address ? req.query.address : 1);
....
getInstance()
方法定义在文件 fronius-meter.ts#L51 中
public static getInstance (id: string): FroniusMeter {
if (id.startsWith('/dev')) {
debug.info('...');
}
let rv = ModbusDevice.getInstance(id);
if (!rv) {
rv = ModbusDevice.instances.find( (d) => (d instanceof FroniusMeter) && (d.address === +id) );
}
return rv instanceof FroniusMeter ? rv : null;
}
源代码在没有警告或错误的情况下被转译 (tsconfig.json),但执行会抛出异常 TypeError: id.startsWith is not a function
。
原因很明显,getInstance()
的调用使用了一个数字作为参数,但是该方法是为字符串作为参数编写的。因此 id.startsWith(...
会抛出一个错误。
我的问题,为什么 typescript 转译没有打印出一些警告或错误?
最佳答案
原因很简单,req.query
is defined as any
.所以req.query.address
也定义为any。
让我们来看这段代码:
let f: TypeA;
let g: TypeB;
let bool: boolean;
let x = bool ? g : f;
Typescript 将推断 x 的类型为 TypeA | B型
。
那么,表达式 req.query.address 的类型? req.query.address : 1
在技术上是 any | number
,但是这只是 any
。
In typescript 3.0 a new type called unknown
is supposed to be added ,这应该可以解决这个问题。
关于 typescript 不检测类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51382574/