Search This Blog

2023/09/10

Typescript:keyof

 type Hero = {

name: string,
power: string,
age: number
}

type HeroKeys = keyof Hero //will be name | power | age

//it will be same as
//type HeroKeys = "name" | "power" | "age"

function getPropery(obj: Hero, key: HeroKeys) {
return obj[key]
}


const myHero: Hero = {
name: "SuperCoder",
power: "Code Manipulation",
age: 30
}

const heroName = getPropery(myHero,'age')
console.log(heroName);

No comments:

Post a Comment