Reputation: 3159
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
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
.
// 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