4

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")
}
1
  • keys is of type string[] not dataTypes[] Commented Jan 8, 2020 at 6:04

3 Answers 3

2

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;
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

  }

Comments

-1

Use:

const temp = m as keyof T;

2 Comments

This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review
@Burimi: This looks like an answer to me. It would definitely benefit from more explanation, and it's not entirely clear to me how it differs from similar answers with slightly different syntax, but it's nevertheless an attempt to answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.