TypeScript中如何安全检查import *导入对象的可选导出属性?
安全实现方案
方案1:类型扩展 + 空值合并(最推荐)
先给导入的模块添加可选的_decode类型定义,既保留类型校验能力,又能适配动态生成的属性:
import * as strings from "../src/string"; // 给strings扩展可选的_decode属性,类型和decode保持一致 type TypedStrings = typeof strings & { _decode?: typeof strings.decode } const typedStrings = strings as TypedStrings const decode = typedStrings._decode ?? typedStrings.decode
方案2:扩展全局模块类型声明
如果多处都会用到_decode属性,可以直接在项目的类型声明文件(比如global.d.ts)中扩展对应模块的类型,后续所有导入处都不用额外处理:
// global.d.ts declare module "../src/string" { export const _decode?: typeof import("../src/string").decode }
业务代码可以直接写:
import * as strings from "../src/string"; const decode = strings._decode ?? strings.decode;
方案3:单次类型断言(轻量适配)
如果只是单次使用,不想额外加类型声明,可以用单次类型断言替代@ts-ignore,只会影响当前属性的类型判断,不会关闭整行的所有类型校验:
import * as strings from "../src/string"; const decode = (strings as any)?._decode ?? strings.decode;
内容的提问来源于stack exchange,提问作者Jose Miralles
相关产品推荐
相关产品推荐

