'TypeScript: Non-Null Assertion Operators with []
I'm aware that I can use the !. syntax to assert that an object has a certain property as follows:
type Person = {
name: string;
age: number;
gender?: string;
}
const myPerson: Person = {
name: 'John Cena',
age: 123,
gender: 'sth'
}
const myFunction = (person: Person) => {
checkIfPersonHasGender(person);
return person!.gender;
}
How do we do that for properties for which keys are in "" such as the following?:
type Person = {
name: string;
age: number;
"my-gender"?: string;
}
I have tried using myPerson!.["my-gender"] but ts gives me an Identifier expected error.
Solution 1:[1]
If you are certain that myPerson["my-gender"] is always defined, you can use TypeScript's type assertion feature to tell TypeScript that myPerson["my-gender"] will never be undefined.
Type Assertion Syntax
// without type assertion
myPerson["my-gender"]; // type ? string | undefined
// using default type assertion syntax
myPerson["my-gender"] as string; // type ? string
// using angle-bracket type assertion syntax
<string> myPerson["my-gender"]; // type ? string
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Christian |
