I have a problem:
- I do not assign for value of variable temp as code below
Please, how to assign value to variable temp
Following code below:
interface Base {
a: number;
b: number;
c: string;
}
interface Child extends Base {
d: string;
}
const data: Child = {
a: 1,
b: 2,
c: "1",
d: "2"
}
function check<T extends Base>(obj: T, key: string) {
const keys: any[] = Object.keys(obj);
type dataTypes = keyof T;
for (let m in keys) {
// error:
// Type 'string' is not assignable to type 'keyof T'.
// Type 'string' is not assignable to type '"a" | "b" | "c"
const temp: dataTypes = m; //error
}
}
function test(data: Base) {
check(data, "d")
}
Object.keys(obj)
returns string[]
, that's why m
is a string, but dataTypes
is "a" | "b" | "c"
(union type), i.e more restrictive. So you can't assign a string to a variable of type "a" | "b" | "c"
.
The solution is simple: don't use Object.keys(obj)
:
function check<T extends Base>(obj: T, key: string) {
type dataTypes = keyof T;
for (let m in obj) {
const temp: dataTypes = m;
}
}
Replace for (let m in keys) {
by for (var i=0; i< keys.length; i++) {
for (var i=0; i< keys.length; i++) {
const temp: dataTypes = keys[i]; //no error
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With