Skip to content

Strange TypeScript errors when a default factory function is specified using method syntax instead of arrow function syntax #1112

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
catrope opened this issue Mar 26, 2022 · 2 comments

Comments

@catrope
Copy link

catrope commented Mar 26, 2022

Minimal example:

<template>
	<div>
		<p>
			{{ joinedWords }}
		</p>
	</div>
</template>

<script lang="ts">
import { defineComponent, PropType } from 'vue';

export default defineComponent( {
	name: 'FooBar',
	props: {
		words: {
			type: Array as PropType<string[]>,
			// Using default: () => [] does not trigger the bug
			default() {
				return [];
			}
		}
	},
	computed: {
		joinedWords() {
			// Using this.words in a computed function, method or lifecycle hook
			// is necessary to trigger the bug
			return this.words.join( '' );
		}
	}
} );
</script>

If you have a component with an array prop that uses method syntax for its default factory function, and that accesses that prop using this.propName in a computed property, you get a strange TypeScript error. The example above produces the following error:

FooBar.vue:27:16 - error TS2339: Property 'words' does not exist on type 'CreateComponentPublicInstance<Readonly<ExtractPropTypes<Readonly<ComponentPropsOptions<Data>>>> & { [x: string & `on${string}`]: undefined; }, ... 16 more ..., { ...; } | {}>'.

27    return this.words.join( '' );

If you use an arrow function instead of method syntax for the default factory function, the bug doesn't happen.

The Vue documentation uses method syntax in its examples for default factory functions, see propE in this code example.

@DannyS712
Copy link

See https://vuejs.org/guide/typescript/options-api.html#typing-component-props, described as a design limitation in typescript, microsoft/TypeScript#38845

@catrope
Copy link
Author

catrope commented Mar 26, 2022

I just found that too. Looks like I should file a bug against Vue instead, to update their documentation to use arrow functions consistently.

@catrope catrope closed this as completed Mar 26, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants