weixin_39608301
weixin_39608301
2021-01-07 12:07

Template ref variable's type is not inferred as expected

I noticed that when I use ref like this, the template ref variable's type is not inferred as expected:


const foo = ref(document.createElement('input'));

I couldn't call its inner method, and its type will be inferred as string:

typescript
onMounted(() => {
    foo.value.focus(); // TS2339: Property 'focus' does not exist on type 'string'.
});

And I found that when I defined the variable like this, it works well:

typescript
const foo = ref<htmlinputelement>(document.createElement('input'));
</htmlinputelement>

Maybe you can see the online example in codesandbox.

Did something go wrong during the process of unwrapping? I noticed that you use statements like [K in keyof T]: UnwrapRef2<T[K]>; to unwrap the ref value.

Or, did I get something wrong? And how could I use ref correctly?

该提问来源于开源项目:vuejs/composition-api

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

6条回答

  • weixin_39832348 weixin_39832348 4月前

    I think the error occurs because HTMLInputElement.prototype.value is a string, and UnwrapRef<T> seems to be resolved "recursively" on TypeScript.

    点赞 评论 复制链接分享
  • weixin_39608301 weixin_39608301 4月前

    By the way, I tried to use ref with render function as the doc says, but I couldn't get the ref( and I couldn't assign ref variables to render function's data option ref). I noticed that after mounted, it still seems to be null:

    ts
    import {createComponent, createElement as h, ref} from '/composition-api';
    
    export default createComponent({
      setup() {
        const root = ref(null);
    
        onMounted(() => {
          console.log(root); // null
        });
    
        return () => h('div', {
          ref: root as any
        });
      }
    });
    
    点赞 评论 复制链接分享
  • weixin_39538687 weixin_39538687 4月前

    Read this https://github.com/vuejs/composition-api#template-refs

    点赞 评论 复制链接分享
  • weixin_39608301 weixin_39608301 4月前

    😅 I'm sorry, I should read all the docs carefully. And what about the previous question? tks.

    点赞 评论 复制链接分享
  • weixin_39538687 weixin_39538687 4月前

    type infer of ref can't work always as expected now. Explicitly specifying the type by ref<Type> is fine.

    点赞 评论 复制链接分享
  • weixin_39608301 weixin_39608301 4月前

    OK. Thanks a lot.

    点赞 评论 复制链接分享

相关推荐