I want to dynamically modify values in the object:
interface myType {
id: number;
name: string;
}
const formFields: (keyof myType)[] = ['id', 'name']
let test: myType= {
id: 0,
name: `name`
}
let data: string[] = ['1', 'Name']
for (let i = 0; i < data.length; i++) {
const field = formFields[i];
if (typeof test[field] === 'number') {
test[field] = Number(data[i]);
} else if (typeof test[field] === 'string') {
test[field] = data[i];
}
}
but I can’t avoid this error:
Type 'number' is not assignable to type 'never'.(2322)
Although it doesn’t affect the actual operation.
6
In JS/TS properties may have getters and setters and their types may differ. You check type of what the getter returns, but setter may accept a different type. Look at this example:
const obj = {
val: "",
get prop(): string {
return this.val;
},
set prop(val: number) {
this.val = val.toString()
},
}
// The following assignment does not compile:
if (typeof obj.prop === "string") { // here prop looks like a string property
obj.prop = "str" // but here prop is already a number property
}
This example should clarify why TS behaves like that.
Q: But why the type of the property is inferred as never
?
A: Compiler has some knowledge about the type of getter, but nothing about the setter. Thus, it can’t guarantee type-safe assignments. The never
type is the one you can never assign to. It prevents you from making unsafe assignments, but you can bypass it (see bellow).
Bellow are two options for you to solve the issue.
The first option keeps your logic and just bypasses the TS error:
(in fact, it’s not type safe and may be misused)
interface type {
id: number;
name: string;
}
const formFields: (keyof type)[] = ['id', 'name']
let test: type = {
id: 0,
name: `name`
}
let data: string[] = ['1', 'Name']
for (let i = 0; i < data.length; i++) {
const field = formFields[i];
if (typeof test[field] === 'number') {
setTestField(field, Number(data[i]))
} else if (typeof test[field] === 'string') {
setTestField(field, data[i])
}
}
function setTestField<T extends keyof type>(key: T, value: type[T]): void {
test[key] = value
}
Or a shorter variation of this option is provided here by @jcalz.
And the second option is a slight rewrite of your logic:
interface type {
id: number;
name: string;
}
const formFields: (keyof type)[] = ['id', 'name']
let test: type = {
id: 0,
name: `name`
}
let data: string[] = ['1', 'Name']
for (let i = 0; i < data.length; i++) {
const field = formFields[i];
switch (field) {
case 'id':
test.id = Number(data[i]);
break;
case 'name':
test.name = data[i]
break;
}
}
Maybe one of them will work for your case.
4