TypeScript调用animate方法时如何设置alternate动画方向
报错原因
这个类型错误是TypeScript默认的类型拓宽机制导致的:单独声明options对象时,TS会把direction字段的"alternate"值推断为通用string类型,但animate()方法要求direction必须是PlaybackDirection类型(仅接受"normal" | "reverse" | "alternate" | "alternate-reverse"四个固定字符串值),通用string类型不符合窄类型约束,就会抛出类型错误。
解决方法
任选一种方案即可修复问题,不建议用any或者as string强行绕过类型检查,会丢失TS的代码提示和校验能力:
- 方案1:给配置对象显式标注官方内置类型
TS的DOM类型库已经预置了animate方法配置项的类型KeyframeAnimationOptions,直接给options标上这个类型即可,所有字段都会获得正确的类型约束和提示:animate() { const progress = document.querySelector(".progress") as HTMLElement; if (progress !== null){ const options: KeyframeAnimationOptions = { duration: 2000, easing: "ease-in-out", iterations: 2, direction: "alternate" // 此处不会再报类型错误 } progress.animate({ width: ["0%", "10%", "20%", "30%", "40%", "50%", "60%", "70%", "80%", "80%", "80%"], backgroundSize: ["0%", "1000%", "500%", "333%", "250%", "200%", "166%", "142%", "125%", "125%", "125%"] }, options); } } - 方案2:用
as const收窄对象类型
不想显式写类型标注的话,给options对象加as const断言,就能阻止TS把字符串值拓宽为通用string类型,保留精确的字面量类型:const options = { duration: 2000, easing: "ease-in-out", iterations: 2, direction: "alternate" } as const; - 方案3:直接把配置写在animate参数位
不单独定义options变量,直接把配置对象作为第二个参数传入animate(),TS会根据方法的参数类型做上下文推导,不会触发类型拓宽:progress.animate( { width: ["0%", "10%", "20%", "30%", "40%", "50%", "60%", "70%", "80%", "80%", "80%"], backgroundSize: ["0%", "1000%", "500%", "333%", "250%", "200%", "166%", "142%", "125%", "125%", "125%"] }, { duration: 2000, easing: "ease-in-out", iterations: 2, direction: "alternate" // 直接写在参数位不会报错 } );
内容的提问来源于stack exchange,提问作者Antonio Argentieri
相关产品推荐
相关产品推荐

