vue
vue copied to clipboard
`this` type inference doesnt work in `data` method
Version
2.6.14
Reproduction link
Steps to reproduce
create a Vue app using vue create
either 2.x or 3.x doesnt matter, as long as it is with TypeScript and object style component syntax
go to HelloWorld.vue
and right below the props definition paste this:
data (): { hellStringType: string, hellNumberType: number, hellInvalid: string} {
debugger;
return {
hellStringType: this.getNumber(),
// should fail due to field type and return type not matching
hellNumberType: this.getNumber(),
// should fail due to there being no such function
hellInvalid: this.buildSomethingElse(),
}
},
methods: {
getNumber (): number {
return 42
}
}
What is expected?
type inference for the method calls should work, and thus the compilation should fail
What is actually happening?
type inference doesnt work, the invalid code compiles fine. Type inference works only for props.
running the code in a browser with debug statement, the methods called are accessible
I have this issue too
I have the same issue
interface IDropdownItem {
selector: string,
handler: number,
title: string,
}
interface HeaderData {
isShowDropdown: boolean
dropdownItems: Array<IDropdownItem>
}
I have such interfaces for describing the data
data(): HeaderData {
return {
isShowDropdown: false,
dropdownItems: [
{
selector: 'SELECTOR-1',
handler: '123',
title: 'TITLE-1',
},
{
selector: 'SELECTOR-1',
handler: '123',
title: 'TITLE-1',
},
]
};
},
in this case, the typescript highlights the incorrect typing of the "handler" field
if I change one of the "handler" fields to the expected type, only the wrong field will be highlighted. This corresponds to the expected behavior
But if I pass a function to one of the fields, and leave the second field with the wrong type, then both fields will be considered correct
If the function is set as a callback, then typing works fine
可以看看这个demo,好像ts是会有这个问题