TypeScript是否允许不为函数入参定义interface直接使用?
解决方案
方案1:全局关闭隐式any校验
直接修改项目根目录的tsconfig.json,在compilerOptions中添加/修改配置:
{ "compilerOptions": { "noImplicitAny": false } }
注意:该配置会关闭全局的隐式any类型报错,会大幅降低TS的类型检查能力,丢失TS的大部分优势,仅适合对类型要求极低的项目使用。
方案2:仅给当前函数参数标记any类型
不需要定义interface,直接给解构的参数整体标记any即可,仅需要修改一行代码:
// 仅在参数解构的括号后加:any即可解决报错 export const adjustElements = ({ from, to, coords }: any) => { let to_rect = to.getBoundingClientRect(), width = to_rect.width * ((coords[0] - 1) * 0.5), height = to_rect.height * ((coords[1] - 1) * 0.5); from.style.top = (to_rect.top + height) + "px"; from.style.left = (to_rect.left + width) + "px"; }
该方案不会影响全局TS配置,仅当前函数的参数不做类型校验,改造成本极低,适合需要快速解决报错的场景。
方案3:行内写类型(无需单独定义interface)
如果想要保留TS的类型检查能力,又不想单独抽离定义interface,可以直接把类型写在参数行内,不需要给interface起额外名称:
export const adjustElements = ({ from, to, coords }: { from: HTMLElement, to: HTMLElement, coords: [number, number] }) => { let to_rect = to.getBoundingClientRect(), width = to_rect.width * ((coords[0] - 1) * 0.5), height = to_rect.height * ((coords[1] - 1) * 0.5); from.style.top = (to_rect.top + height) + "px"; from.style.left = (to_rect.left + width) + "px"; }
该方案兼顾了类型检查和开发效率,不需要额外维护interface定义文件,适合对类型有一定要求的场景。
内容的提问来源于stack exchange,提问作者user670290
相关产品推荐
相关产品推荐

