Typescript inferred types for child components that has done type checking #2262
-
That title is a mouthful, let me explain it better. Imagine that you have a store with a random state: export const useFoo = defineStore('fooStore', () => {
const username = ref(undefined as string | undefined);
return { username };
}); And inside <Child v-if="typeof username !== 'undefined'" /> And <script setup lang="ts">
const foo = useFoo();
const { username } = storeToRefs(foo);
</script> Now, if I want to do anything meaningful inside const onClick = () => {
username.value // undefined | string
if (typeof username === 'undefined') {
// This will never happen(as long as that if-statement in app.vue exists)
// It's only here for compile time checks.
return;
}
username.value // string
} It's a bummer that I need to add this check just to make typescript happy when I know for a fact that I suppose you can use props. But doesn't feel scalable to do so when there could be a lot of sub components between |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
The issue doesn't stem from Pinia here, rather from the fact that because you have this code in the |
Beta Was this translation helpful? Give feedback.
The issue doesn't stem from Pinia here, rather from the fact that because you have this code in the
Child
component, there is nothing to indicate to typescript that the value is populated. You could just as well use this component elsewhere and not have that check.If you are truly certain that the component won't be used elsewhere and the
username
will therefore always be populated, a simpler way to appease typescript would be to use the ! to mark it as definitely having a value =>username.value!
.