[英]Object is possibly 'undefined' typescript
I am trying to access the value from an object. 我试图从一个对象访问值。 But I get the following error.
但是我收到以下错误。
Object is possibly 'undefined' typescript
对象可能是“未定义”打字稿
My TypeScript code: 我的TypeScript代码:
import { SqlClient } from 'msnodesqlv8';
declare var require: any;
const sql: SqlClient = require('msnodesqlv8');
const connectionString =
'server=.,1433;Database=emps;Trusted_Connection=Yes;Driver={SQL Server Native Client 11.0}';
const query = 'SELECT * FROM [dbo].[sample] WHERE id = 117';
sql.query(connectionString, query, (err, rows) => {
console.log(rows); // this works fine, but when i try to access its value using object key, it fails
console.log(rows[0].Id); // this fails
});
This works fine in JavaScript. 在JavaScript中可以正常工作。 What is the TypeScript way of doing it.
TypeScript的实现方式是什么。
You're getting that error because if the rows
array doesn't contain any elements, then rows[0]
will be undefined. 之所以会出现此错误,是因为如果
rows
数组不包含任何元素,那么rows[0]
将是未定义的。 Two possible solutions: 两种可能的解决方案:
1) Check that it actually has data, eg 1)检查它是否确实有数据,例如
if (rows[0]) {
console.log(rows[0].Id)
}
2) Disable the strict
or strictNullChecks
option in your tsconfig.json
(see more here ). 2)禁用
strict
或strictNullChecks
在您选择tsconfig.json
(详见这里 )。 This will silence the error, but you'll get a runtime error if it actually is undefined, so you may want to check the value instead unless you're absolutely certain it will always have data. 这将沉默的错误,但你会得到一个运行时错误,如果它实际上是不确定的,所以你可能要检查,而不是,除非你是绝对肯定它会永远有数据的价值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.