Reputation: 11671
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?
Upvotes: 0
Views: 33
Reputation: 674
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"
Upvotes: 3