我有一个返回对象的函数.稍后,此对象将使用属性(例如$watch
)进行扩展:
export default () => {
const myObject = {
property1: 'string1',
property2: 1,
init() {
console.log('property1', this.property1)
this.$watch('property1', (value) => {
console.log('property1 changed', value)
})
},
}
return myObject
}
interface OtherProps<T> {
$watch: <K extends keyof T | string, V extends K extends keyof T ? T[K] : any>(
property: K,
callback: (newValue: V, oldValue: V) => void,
) => void;
// ... other props
}
有没有办法把OtherProps
的属性注入到myObject
,这样TypeScript就不会说Property '$watch' does not exist on type ...
了?
我设法以这种方式输入了它,但对于我的口味来说,它有点太冗长了,因为我必须单独输入定义:
type WithProps<T> = ThisType<T & OtherProps<T>>
type Test = WithProps<{
property1: string
property2: number
init(): void
}>
export default () => {
const myObject: Test = {
property1: 'string1',
property2: 1,
init() {},
}
return myObject
}
我找到了this answer个,看起来很管用,但我很难根据我的情况来调整它.