简体   繁体   中英

use object keys as type in typescript

consider we have a defined/constant object like below that we want to use it's keys as a type;

const componentDetail = {
  "ejareRaf" : {
    text : "rented",
    background : "linear-gradient(0deg, rgba(243, 7, 27, 0.6), rgba(243, 7, 27, 0.6));"
  },
  "hamahangBazdid" : {
    text : "visit-set", 
    background : "rgba(13, 81, 55, 0.6)"
  },
  "onMozakere" : {
    text : "negotitaing", 
    background : "linear-gradient(0deg, rgba(217, 171, 33, 0.6), rgba(217, 171, 33, 0.6));"
  },
  "dideShod" : {
    text : "seen", 
    background : "rgba(18, 25, 33, 0.4)"
  },
  "cancelBazdid" : {
    text : "canceled", 
    background : "rgba(238, 45, 123, 0.3)"
  },
}

now I want a type deduced from object keys above like this:

"ejareRaf" | "hamahangBazdid" | "onMozakere" | "dideShod" | "cancelBazdid"

after several trial and error I'd found it myslef:

type componentDetailKeys = keyof typeof componentDetail;

// "ejareRaf" | "hamahangBazdid" | "onMozakere" | "dideShod" | "cancelBazdid"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM