Abhishek VG
Abhishek VG

Reputation: 1

Typescript type pattern is not working on return from array

I want to have a list of array whose string pattern are /key-/, I am using typescript, but getting type error for keysArray. I Need help in fixing the type error for keysArray. Thank you

const temp: any = {a:1, b:2, "key-1":3, c:4, "key-2":5}


type IKey = `key-${number}`

const keysArray: IKey[] = Object.keys(temp).filter((eachKey: any) => /key-/.test(eachKey));


interface ISome {
    [key: IKey]: string
}

const obj: ISome = {
    "key-1": "hello"
}

Link to the demo here

I tried adding as unknown as IKey to the filter function, that didn't resolve the type error

Upvotes: 0

Views: 29

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 84912

If you want .filter to product an array with narrowed types, you need to make your function into a type guard. Ie, it needs the special return type "eachKey is IKey":

const keysArray: IKey[] = Object.keys(arr).filter(
  (eachKey: string): eachKey is IKey => /key-/.test(eachKey)
);

Playground link

P.S, i think it's a mistake that you used Object.keys(arr).filter here. Object.keys(arr) is going to give you an array of ["0", "1", "2", 3", /*etc*/]. Ie, the indexes of the array. Instead you probably meant to do arr.filter

Upvotes: 1

Related Questions