简体   繁体   English

Typescript 类型模式在从数组返回时不起作用

[英]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.我想要一个字符串模式为 /key-/ 的数组列表,我正在使用 typescript,但出现 keysArray 的类型错误。 I Need help in fixing the type error for keysArray.我需要帮助来修复 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我尝试将as unknown as IKey添加到过滤器 function,但没有解决类型错误

If you want .filter to product an array with narrowed types, you need to make your function into a type guard .如果您希望.filter生成具有缩小类型的数组,则需要将 function 设置为类型保护 Ie, it needs the special return type "eachKey is IKey":即,它需要特殊的返回类型“eachKey is IKey”:

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

Playground link 游乐场链接

PS, i think it's a mistake that you used Object.keys(arr).filter here. PS,我认为你在这里使用Object.keys(arr).filter是一个错误。 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 Object.keys(arr)将为您提供["0", "1", "2", 3", /*etc*/]的数组。即数组的索引。相反,您可能打算做arr.filter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM