6
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

TypeScriptの"Object is possibly undefined"への対処

Last updated at Posted at 2021-11-11

DynamoDBをTypescriptから呼び出していて,起こったエラー

const result = await DBAccess.getItem(params);

const status:string = result.status.S;

ここで,左辺のstringと,右辺のstring | undefinedで型の不一致が起きているのがひとつ
さらに,resultundefinedになる可能性があるというエラーが起きる.
以下のように解決した.
resultundefinedになる可能性をあらかじめ排除しておき,そのうえで型アサーションをする.

const result = await DBAccess.getItem(params);

if (result === undefined) {
  // do something
}

const status:string = (result!.status.S as string)

もっと良い方法があればコメントでおしえてください!

6
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?