Type 'true' is not assignable to type 'Ref<boolean>'

Viewed 1755

I have the following code:

<!-- App.vue -->
<template>
    <button @click="login">Login</button>
</template>
<script lang="ts">
import { loggedIn } from '../state'
import { defineComponent } from 'vue'

export default defineComponent({
    data() {
        return {
            loggedIn,
        }
    },
    methods: {
        login() {
            this.loggedIn = true
        }
    }
})
</script>
// state.ts
import { reactive, ref } from 'vue'

export const loggedIn = ref(true)

The code above has a compilation error (which shows both in VS Code and from vue-cli-service serve)

TS2322: Type 'true' is not assignable to type 'Ref<boolean>'.

  >  |             this.loggedIn = true

I'm pretty sure that's how I'm supposed to do it, so I'm not sure why I'm getting an error. I can change the code to this and the error goes away: this.loggedIn.value = true But I'm pretty sure that's not how its supposed to work, and I get this runtime error:

Cannot create property 'value' on boolean 'false'

Why am I getting this compilation error in my original code?

1 Answers

Source: https://codesandbox.io/s/sad-cdn-ok40d

App.vue

<!-- App.vue -->
<template>
  <div>
    <button @click="login">Login</button>
    <div>{{ data }}</div>
  </div>
</template>
<script lang="ts">
import { loggedIn } from "./state";

export default {
  name: "App",
  setup() {
    const data = loggedIn();
    const login = () => (data.value = !data.value);
    return { data, login };
  },
};
</script>

State.ts

import { ref } from "vue";

export const loggedIn = () => ref(false);

Main.js

import { createApp } from "vue";
import App from "./App.vue";

createApp(App).mount("#app");

So the thing is, if we use the composition API, we should use the setup() method to setup out data and methods.

Since ref uses the .value to change the value, we don't need reactive.

Reactive is used for object values - which it will add a Proxy to watch over the key/values of the object.

In this case, we should use ref.

Related