How to use Optional Chaining In Typescript
In this approach, we are using optional chaining in TypeScript, we access the value associated with the “language” key within the object obj. The result, is then converted to uppercase which is stored in the variable res, which contains “TYPESCRIPT” and is then printed to the console.
Syntax:
object?.property
object?.method()
object?.[expression]
Example: The below example uses Optional Chaining to Get an Object Value By Key in TypeScript.
const obj: { name?: string; category?: string; language?: string } = {
name: "w3wiki",
category: "Programming",
language: "TypeScript",
};
const res: string | undefined = obj.language?.toUpperCase();
console.log(res);
Output:
"TYPESCRIPT"
How to Get an Object Value By Key in TypeScript
In TypeScript, we can get an object value by key by accessing the specific properties within the objects of the dynamic type. This can be done using Dot Notation, Bracket Notation, and Optional Chaining. In this article, we will explore all these approaches along with their implementation in terms of examples and outputs.
Table of Content
- Using Dot Notation
- Using Bracket Notation
- Using Optional Chaining
- Using Object.hasOwnProperty() Method
- Using Object.entries() and Array.find()
- Using Object.keys() Method