Typescript 写入类型保护,将类型T缩小到数组<;K>;

Typescript 写入类型保护,将类型T缩小到数组<;K>;,typescript,typescript-generics,Typescript,Typescript Generics,我有一个javascript函数,用于检查是否有任何输入值是数组: function isArray<T, K>(value: T): value is Array<K> { return Array.isArray(value); } 函数isArray(值:T):值为数组{ 返回数组.isArray(值); } 如何将其正确转换为typescript泛型类型保护,以便它可以接受任何值并返回一些数组 最后,我希望Typescript理解以下代码: ... i

我有一个javascript函数,用于检查是否有任何输入值是数组:

function isArray<T, K>(value: T): value is Array<K> {
    return Array.isArray(value);
}
函数isArray(值:T):值为数组{
返回数组.isArray(值);
}
如何将其正确转换为typescript泛型类型保护,以便它可以接受任何值并返回一些数组

最后,我希望Typescript理解以下代码:

...
if (isArray(style)) {
  // here Typescript understands style is Array<TextStyle>
  for (const textStyle of style) {
    if (hasDefinedProperty(textStyle, "lineHeight")) lineHeight = textStyle.lineHeight;
    if (hasDefinedProperty(textStyle, "fontSize")) fontSize = textStyle.fontSize;
  }
  if (typeof lineHeight !== 'undefined') style.push({ lineHeight })
}
。。。
if(isArray(样式)){
//在这里,Typescript理解样式是数组
for(常量文本样式的样式){
如果(hasDefinedProperty(textStyle,“lineHeight”))lineHeight=textStyle.lineHeight;
如果(hasDefinedProperty(textStyle,“fontSize”))fontSize=textStyle.fontSize;
}
if(typeof lineHeight!=='undefined')style.push({lineHeight})
}

类型防护装置用于缩小类型。你不能局限于泛型的K,K需要更具体的东西。类型防护装置是到达最终类型的工具。您可以缩小到数组,但X需要是某种特定类型。考虑:
函数isArray(值:未知):值是数组{return Array.isArray(值);}函数isStrArray(值:数组):值是数组{return typeof value[0]======'string'}
在示例代码中声明的
样式
的类型是什么?当你说“TypeScript理解
style
Array
”时,
TextStyle
类型是什么?现在这似乎不是一个好主意。根据您的定义,您只需使用
if(Array.isArray(style)){…}
即可。如果没有,那么我们需要更多的信息。祝你好运