为何TypeScript无法根据参数确定函数返回类型?
TypeScript中sha256函数返回类型推断问题的解决方案
我编写了一个sha256函数,设计逻辑为:传入encoding参数时返回string类型,否则返回Buffer类型,原始代码如下:
import { createHash } from "crypto"; // 指定encoding时返回string,否则返回Buffer const sha256 = (data: string | string[], encoding?: BinaryToTextEncoding) => { const hash = createHash("sha256"); if (Array.isArray(data)) { data.forEach((s) => hash.update(s)); } else { hash.update(data); } if (encoding) { // 返回string类型 return hash.digest(encoding); } // 返回Buffer类型 return hash.digest(); }; // 为什么hashed的类型不是string而是string | Buffer? const hashed = sha256(["a", "b"], "hex");
实际使用时,即便传入了encoding参数"hex",TypeScript仍将hashed的类型识别为string | Buffer,不符合预期。
经提示,使用函数重载可以解决该问题,重载后的代码如下:
function sha256(data: string, encoding: BinaryToTextEncoding): string; // eslint-disable-next-line no-redeclare function sha256(data: string[], encoding: BinaryToTextEncoding): string; // eslint-disable-next-line no-redeclare function sha256(data: string[]): Buffer; // eslint-disable-next-line no-redeclare function sha256(data: string): Buffer; // eslint-disable-next-line no-redeclare function sha256(data: string | string[], encoding?: BinaryToTextEncoding) { const hash = createHash("sha256"); if (Array.isArray(data)) { data.forEach((s) => hash.update(s)); } else { hash.update(data); } if (encoding) { return hash.digest(encoding); } return hash.digest(); }
注意事项
- 需要禁用ESLint的
no-redeclare规则(通过注释// eslint-disable-next-line no-redeclare实现); - 必须使用函数声明而非箭头函数定义该函数,因为TypeScript不支持箭头函数的重载语法。
内容的提问来源于stack exchange,提问作者user3357926
相关产品推荐
相关产品推荐

