Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

typescript - Is it possible to use `keyof` operator on literals instead of interfaces?

I have an object literal such as the following (all properties are known at compile time):

const foo = {
  "hello": "hola"
};

If foo were an interface rather than a variable, I could easily do something like

/** THEORETICAL ONLY - Does not compile! */
function translate(input: keyof foo): string {
  return foo[input];
}

However, doing so with a variable does not work, since the compiler cannot find an interface with the name foo.

Does Typescript support keyof operations on object literals whose values are known at compile time?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

keyof operates on types, but foo is a value. But the typeof operator takes a value and produces its type, so you can use keyof typeof foo to do this.

Note that this only works if you haven't associated an interface with the object literal (thanks radicand).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...