为什么';t TypeScript窄类型在只能返回窄类型的映射之后?

为什么';t TypeScript窄类型在只能返回窄类型的映射之后?,typescript,Typescript,在下面的代码中,我希望find函数返回undefined | BufferEncoding,与Map的类型相同。但是返回undefined | string。为什么 const chartdetToFsEncodings = new Map<string, BufferEncoding>([ ["UTF-8", "utf8"], ["UTF-16LE", "utf16le"], ]); const supportedEncoding = analyse(

在下面的代码中,我希望find函数返回
undefined | BufferEncoding
,与Map的类型相同。但是返回
undefined | string
。为什么

  const chartdetToFsEncodings = new Map<string, BufferEncoding>([
    ["UTF-8", "utf8"],
    ["UTF-16LE", "utf16le"],
  ]);

  const supportedEncoding = analyse(buffer)
    .map((match) => match.name)
    .find((name) =>
      chartdetToFsEncodings.get(name)
    ) as BufferEncoding;
const chartdetofsencodings=新地图([
[“UTF-8”、“utf8”],
[“UTF-16LE”、“utf16le”],
]);
常量supportedEncoding=分析(缓冲区)
.map((匹配)=>match.name)
.find((名称)=>
chartdetToFsEncodings.get(名称)
)作为缓冲编码;
我尝试将映射设置为const,但出现了一些语法错误

  const chartdetToFsEncodings = new Map<string, BufferEncoding>([
    ["UTF-8", "utf8"],
    ["UTF-16LE", "utf16le"],
  ]) as const;
const chartdetofsencodings=新地图([
[“UTF-8”、“utf8”],
[“UTF-16LE”、“utf16le”],
])作为常量;

问题归结为不正确地使用了
Array.prototype.find
。该方法的作用类似于过滤器,但只返回谓词返回true的数组中的第一个元素。在这种情况下,它可以从映射数组中返回一个元素,从
.map(match=>match.name)
,该数组的类型为
string
,或
未定义的

如果您想获得一个
缓冲编码数组
,可以直接在
.map()
回调中执行:

const supportedEncoding = analyse(buffer)
    .map((match) => chartdetToFsEncodings.get(match.name))

find
方法由
string[]
使用,因此它将返回
string | undefined
。如果要使
缓冲编码|未定义
,这是最简单的方法:

const supportedEncoding=analysis(缓冲区)
.map((匹配)=>match.name)
.find((名称):名称为BufferEncoding=>
chartdetToFsEncodings.get(name)!==未定义
);

表达式的类型是什么
analysis(buffer.map)((match)=>match.name)
?给定给
find
的函数的预期返回类型是什么?
find
是否需要返回类型为
boolean
的值的函数?作为旁注,我不知道是否有任何地方或方法可以查找内置对象的方法的TypeScript类型。当然有MDN,比如,但据我所知,它不包括类型脚本类型。似乎传递给
Array.find
的函数没有返回类型
boolean
,而是“truthy”/“falsy”…@Terry:是的,它是来自第三方库的简单联合类型。在这种情况下,我的最佳解决方案是什么?@MelvinWM:是的,这是正确的。这对打字有关系吗?