2

I just started learning Typescript and need some help with this example.

 const alphabet = { 'a': {lower: 97, upper: 65}, 'b': {lower: 98, upper: 66} } type Char = 'a' | 'b' function printSome(char: Char){ console.log(alphabet[char]) } 

Instead of manually updating the Char type, I'd like to dynamically update generate types from the alphabet object.

    1 Answer 1

    3

    You could use the keyof and typeof operators:

    const alphabet = { 'a': {lower: 97, upper: 65}, 'b': {lower: 98, upper: 66} } type Char = keyof typeof alphabet; function printSome(char: Char){ console.log(alphabet[char]) } 

    This basically turns alphabet into a type and then gets the keys of that type.

    5
    • Thanks for looking into this. I tried that and it doesn't work for me for some reason. I'm getting this error: 'alphabet' refers to a value, but is being used as a type here. Did you mean 'typeof alphabet'? ts(2749)
      – username
      CommentedFeb 16, 2022 at 4:12
    • @AnonymousAnonymous Oops, updated.
      – Cully
      CommentedFeb 16, 2022 at 4:27
    • Nice! It worked. Thanks again. BTW, for some reason why I add an interface or type definition for the alphabet object, it stops working. Any ideas why is that?
      – username
      CommentedFeb 16, 2022 at 4:35
    • @AnonymousAnonymous I would need to see what you're trying to do. If you post another SO question, add a link and I'll take a look.
      – Cully
      CommentedFeb 16, 2022 at 4:40
    • i compiled the second part for my question and posted it here: stackoverflow.com/questions/71136635/…. If you have a chance, please take a took.
      – username
      CommentedFeb 16, 2022 at 5:01

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.