Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR TYPESCRIPT

typescript get object property by name

// Type
type UserType = {
	name: string;
    email: string;
};

// Object
const user: UserType = {
	name: "Bob",
    email: "bob@bob.com"
};

// Get Object property by name
const name = user["name" as keyof UserType] // name = "Bob"

// Alternatively, create object property type
type ObjectKey = keyof typeof user; // type ObjectKey = "name" | "email"

const myKey = "name" as ObjectKey;
const name = user[myKey]; // name = "Bob"
Source by bobbyhadz.com #
 
PREVIOUS NEXT
Tagged: #typescript #object #property
ADD COMMENT
Topic
Name
9+7 =