0

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.

3
  • wh ynot check for undefined before the log ? Commented Apr 25, 2019 at 20:42
  • 1
    Use an if statement Commented Apr 25, 2019 at 20:44
  • 1
    declare var require: any; const sql: SqlClient = require('msnodesqlv8'); is very wrong (FYI). It most definitely needs to be import sql = require('msnodesqlv8'); or import sql from 'msnodesqlv8'; Commented Apr 25, 2019 at 20:55

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It's a really bad idea to reduce strictness. If you need to override it on a specific value, adjust the type of that value.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.