I have the following situation:
const data = {
bmw: 10,
opel: 2
}
type customType = keyof typeof data
const myKey = 'bmw';
console.log(data[myKey as customType])
Doing this data[myKey as customType]
i want to access the key from data
. I read that using as
we use type casting
and this is not very safe.
Question : How to rewrite the code above avoiding the use of as
operator?
Your code compiles perfectly well if you simply remove the typecast. Like so:
const data = {
bmw: 10,
opel: 2
}
type customType = keyof typeof data
const myKey = 'bmw';
console.log(data[myKey])
This is because you have defined myKey
as a const variable, which means it has the type bmw
(since it can never change) which is assignable the index type of 'bmw' | 'opel'
'bmw' | 'opel'
just define your variable as customType
:
const data = {
bmw: 10,
opel: 2
}
type customType = keyof typeof data
const myKey: customType = 'bmw';
console.log(data[myKey])
or directly:
const myKey: keyof typeof data = 'bmw';
specifying that myKey
is of type customType
will ensure that you can put only bmw
or opel
as a value, otherwise will produce compilation error; therefore is slightly "safer" than "as".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.