user2281858
user2281858

Reputation: 1997

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:

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. What is the TypeScript way of doing it.

Upvotes: 0

Views: 2133

Answers (1)

John Montgomery
John Montgomery

Reputation: 7106

You're getting that error because if the rows array doesn't contain any elements, then rows[0] will be undefined. Two possible solutions:

1) Check that it actually has data, e.g.

if (rows[0]) {
    console.log(rows[0].Id)
}

2) Disable the strict or strictNullChecks option in your tsconfig.json (see more here). 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.

Upvotes: 3

Related Questions