Bootstrap 5.2 Tooltip placement函数签名不匹配TS编译错误
问题描述
我使用Webpack编译以下Bootstrap 5.2.3代码:
$('[data-bs-toggle="tooltip"]').tooltip({ placement: function(tt, trigger) { return 'top'; }, });
出现TypeScript编译错误:
TS2322: Type '(tt: any, trigger: any) => string' is not assignable to type 'PopoverPlacement | (() => PopoverPlacement)'.
移除(tt, trigger)参数后代码可正常运行,但我需要trigger参数来识别触发Tooltip的元素。根据Bootstrap 5.2官方文档,placement函数应接收两个参数:
当使用函数确定位置时,会将Popover DOM节点作为第一个参数,触发元素DOM节点作为第二个参数传入,this上下文指向Popover实例。
为何符合文档定义的参数会导致编译错误?
问题原因
这是Bootstrap 5.2.x版本的TypeScript类型定义与实际运行逻辑不一致导致的:官方文档明确说明placement函数支持两个参数,但当时的@types/bootstrap包(或Bootstrap内置类型)中,placement的类型仅定义为无参函数或固定位置枚举值,并未包含带参数的函数类型,因此TypeScript会抛出类型不匹配的错误。
解决方案
1. 类型断言快速绕过
直接用as any断言placement函数,强制TypeScript跳过类型检查:
$('[data-bs-toggle="tooltip"]').tooltip({ placement: function(tt, trigger) { // 可正常使用trigger参数做逻辑处理 return 'top'; } as any, });
2. 扩展类型定义(推荐)
创建自定义类型声明文件(比如bootstrap.d.ts),扩展Tooltip的选项类型,修正placement的函数定义:
import { TooltipOptions, PopoverPlacement } from 'bootstrap'; declare module 'bootstrap' { interface TooltipOptions { placement?: PopoverPlacement | ((tooltipElement: HTMLElement, triggerElement: HTMLElement) => PopoverPlacement); } }
确保该文件被TypeScript识别(可在tsconfig.json的include数组中添加文件路径),之后即可正常使用带参数的placement函数,同时保留类型检查。
3. 升级Bootstrap版本
Bootstrap 5.3及以上版本已修复该类型定义问题,升级后无需额外处理,直接使用符合文档的带参数placement函数即可。
内容的提问来源于stack exchange,提问作者Raj

