0
votes

I'm trying to store typescript object with key as string and value as number | number [] | string.

interface Person {
  [ key : string] : number | number[] | string
}

const person:Person = {
"name" : "Harsha",
"marks" : [ 89, 90 , 100 , 67],
"class" : 8
}

function hundredsCount(marks: number[]) {
  const count:number = marks.map((each:number) => each).length
}

hundredsCount(person[marks])

When I call hundredsCount then facing an error : Argument of type 'string | number | number[]' is not assignable to parameter of type 'number[]'. Type 'string' is not assignable to type 'number[]'.

1
the brackets are misplaced inside hundredsCount functionRamesh Reddy
Invoke your method as follows: hundredsCount(person.marks) or hundredsCount(person["marks"])uminder
@uminder I tried both ways but no luckshree harsha

1 Answers

0
votes

The problem is that you have declared type Person as very wide type which can have any string keys, with three different type of values. It means that when you access any of those properties of the value representing Person TS can't distinguish the type of it from what declaration says - number | number[] | string.

The solution is to have more strict type:

interface Person {
    name: string,
    marks: number[],
    'class': number,
}

After that person['marks'] is inferred as number[].


If the type cannot be so specific, lets say there are dynamic keys, but you know that such thing like marks key is there, then we can have such more wide type:

interface Person {
    [ key : string] : number | number[] | string
    marks: number[]
}

Additionally if you try to access person[k] where k is just a string value, then there need to be used typeguard in order to properly specify the type:

function f(k: string) {
    if (k === 'marks') {
        hundredsCount(person[k]); // inside if person[k] is known as number[]
    }
    // outside person[k] is known as number | number[] | string

}