typescript | 怎么实现类似vue那样的类型提示?

下面是我的.ts文件,我想实现当输入d.的时候,给我提示d.a,d.b,d.sayHello等等,我该咋写?

type AnyObject = {

[prop: string]: any

} & Object

type MethodsType = {

[name: string]: Function

}

class Vue {

[x: string]: any

constructor({

data = {},

methods = {}

}: { data?: AnyObject, methods?: MethodsType }) {

const result: AnyObject = {}

for (const key in data) {

if (Object.prototype.hasOwnProperty.call(data, key)) {

result[key] = data[key]

}

}

for (const key in methods) {

if (Object.prototype.hasOwnProperty.call(methods, key)) {

if (result[key]) throw Error('重名属性')

result[key] = methods[key].bind(result)

}

}

return new Proxy(this, {

get(_, p) {

if (p in data || p in methods) {

return Reflect.get(result, p)

}

}

})

}

}

const d = new Vue({

data: {

a: 1,

b: 2,

c: 'abc'

},

methods: {

sayHello() {

console.log(this)

}

}

})

// # that can tip

d.?


回答:

问题已解决,主要关键字是泛型,我这里贴个简单代码

type AnyObject = {

[prop: string]: any;

}

type MethodsType = {

[name: string]: Function;

};

function Vue<

T extends AnyObject,

D extends MethodsType

>({ data, methods }: { data: T; methods: D }): T & D {

return {

...data,

...methods

}

}

const d = Vue({

data: {

a: 1,

b: 2,

c: 'abc',

},

methods: {

sayHello() {

console.log(this);

},

},

});


回答:

你这个方法实现应该就有问题,new Vue()并不会返回new Proxy(), 而是返回Vue的实例;
而你的Vue实例中也没有a,b,c属性,肯定无法取到a,b,c;

另外 就算 new Vue 返回的是new Proxy(this),但new Proxy(this)其实就是this, 仍然是Vue的实例,所以只有Vue中存在属性a,b,c,才能读取

可以这样试试

type AnyObject = {

[prop: string]: any;

};

type MethodsType = {

[name: string]: (...args: any) => any;

};

class Vue<T extends AnyObject, U extends MethodsType> {

$attrs?: T;

$method?: U;

constructor({ data, methods }: { data?: T; methods?: U }) {

const result: AnyObject = {};

for (const key in data) {

if (Object.prototype.hasOwnProperty.call(data, key)) {

result[key] = data[key];

}

}

for (const key in methods) {

if (Object.prototype.hasOwnProperty.call(methods, key)) {

if (result[key]) throw Error('重名属性');

result[key] = methods[key].bind(result);

}

}

this.$attrs = data;

this.$method = methods;

new Proxy(this, {

get(_, p) {

if (p in (data || {}) || p in (methods || {})) {

return Reflect.get(result, p);

}

},

});

}

}

const d = new Vue({

data: {

a: 1,

b: 2,

c: 'abc',

},

methods: {

sayHello() {

console.log(this);

},

},

});

// 通过 d.$attr.a访问

d.$attrs.a;

d.$method.sayHello;

以上是 typescript | 怎么实现类似vue那样的类型提示? 的全部内容, 来源链接: utcz.com/p/933024.html

回到顶部