0

I have an js object with two keys, foo and bar.

const x = { foo: '', bar: '' }

Also I have abc function that take value (the value can be foo or bar only).

function abc(value: string) {

 const selected = x[value];
}

currently, value is string type. but I want to have foo or bar (cause I have them in x object). I try to do with

  function abc(value: typeof x)

But typescript doesn't accept that.

How can I change my code to make it work as I expected?

1 Answer 1

3

use keyof the typeof X, it will extract each key of the type of the variable X which are :

{
  foo: string;
  bar: string;
}

This function has to be :

  function abc(value: keyof typeof x)

The type of the value param will be "foo" | "bar"

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.