Can custom hooks have hints and type inference like useTemplateRef? #12470
tbontb-iaq
started this conversation in
Ideas
Replies: 1 comment 2 replies
-
// 假设你在模板中使用了这个模板引用
// <div ref="my_div"></div>
// 定义自定义钩子,支持类型推断
function useMyHooks<RefName extends string>(refName: RefName) {
// 模拟根据 refName 获取到模板引用的类型
// 通过条件类型根据不同的 ref 名称推断对应的元素类型
let ref: RefName extends "my_div" ? HTMLDivElement :
RefName extends "my_button" ? HTMLButtonElement :
never;
// 返回一个类型安全的 ref
return ref;
}
// 使用该钩子时,会自动推断类型
const div = useMyHooks("my_div"); // div 的类型将推断为 HTMLDivElement
const button = useMyHooks("my_button"); // button 的类型将推断为 HTMLButtonElement |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
The newly added
useTemplateRef
is a great feature with ref key hints and type inference provided by@vue/language-tools
. Can this useful feature be enjoyed in user-defined hooks?Before:
After:
I think it might look like this:
Beta Was this translation helpful? Give feedback.
All reactions