How to use for in Typescript The in? I use for… in TS. In has some problems and some solutions. So let’s take a look at the code below.
interface ABC {
a: string
b: string
}
const x: ABC = {
a:'1'.b:'2'
}
const y: ABC = {
a:'3'.b:'4'
}
for (const key in x) {
// Index signature with type "string" could not be found on type "ABC". ts(7053)
x[key] = y[key]
}
Copy the code
This is due to the fact that… The in loop also iterates over inherited attributes, so you cannot determine the type of the key, only string. If you use Object’s hasOwnProperty method, however, it doesn’t work. TS still thinks the key is a string. You need to wrap the hasOwnProperty method yourself.
function hasOwnProperty<T.K extends PropertyKey> (obj: T, prop: K) :obj is T & Record<K.unknown> {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
for (const key in x) {
if (hasOwnProperty(y,key) && hasOwnProperty(x,key)) {
x[key] = y[key]
// let x: ABC & Record
,>
// The type of x is changed}}Copy the code
That’s fine. It’s just too much trouble. I’m just iterating over a simple object, so why bother? There are easy ways to do it. You just have to write it like this as you go through the loop.
let key:keyof ABC
for (key in x) {
x[key] = y[key]
}
Copy the code
I changed the a type of interface ABC to number.
/ / can't type "string | number" type assigned to "never".
// Cannot assign type "string" to type "never". ts(2322)
Copy the code
WTF, why is x[key] changed to never? Because x[key] can be of two types when it is assigned, it can never be of two types, so never? (Personal guess). The same error would be reported if you used the previous method. Since never is the lowest type of TS, never can only be assigned to another type of never, so x[key] cannot be assigned. How can this do, there is no way, can only use the last method!
let key:keyof ABC
//@ts-ignore
for (key in x) {
x[key] = y[key]
}
Copy the code
If you know how to solve it or if you have any questions, please leave a comment below. Thank you.