Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript assign value for keyof not working

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")
}
like image 623
linthertoss Avatar asked Oct 17 '25 14:10

linthertoss


2 Answers

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;
  }
}
like image 87
Kirill Simonov Avatar answered Oct 19 '25 03:10

Kirill Simonov


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

  }
like image 33
Mohamed Farouk Avatar answered Oct 19 '25 04:10

Mohamed Farouk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!