cSharp
cSharp

Reputation: 3159

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.

Upvotes: 0

Views: 423

Answers (1)

Christian
Christian

Reputation: 831

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

Upvotes: 1

Related Questions