Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

typescript - What are the types of keys and values of a string enum?

Say, I have a enum like this:

export enum Lang {
  eng = '????',
  rus = '????',
  jap = '????',
  chi = '????',
}

I have a function that accepts a key of that enum and returns its value:

function langToFlag(key) {
  return Lang[key];
}

Question: How do I type the argument and the return value of this function?

I expected something like:

function LangToFlag(key: keyof Lang): valueof Lang {

...but keyof includes all internal Object properties and valueof does not exist.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try this

enum Lang {
  eng = '????',
  rus = '????',
  jap = '????',
  chi = '????',
}

function langToFlag(key: keyof typeof Lang): Lang {
  return Lang[key];
}

var val = langToFlag("jap");
console.log(val);

Lang is essentially an object, and as such a key of it would be keyof typeof Lang


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...