我如何在数据中省略getter、setter 和方法Partial<>
?
还是存在一种使用 typescript 获得这种架构的方法?
我需要一个具有完全访问权限的类型,以及一个没有 readOnly 的类型。
我试着在这里做一个小例子,见注://
export const $A = (() => {
class A {
_uid?: string = 'generateUID()';
_title?: string = '';
children?: A[] = [];
B?: InstanceType<typeof $B['B']> = $B.create();
get Title() {
return this._title || this._uid;
}
constructor(data: Partial<A> = {}) {
Object.assign(this, data);
}
getFullTitle() {
return this._title + this._uid;
}
}
function create(data?: Partial<A>) {
return new A(data);
}
function renderer(A: A) {
//#1 Allow full access public A in this renderer entity
const { Title, _title, _uid } = A; // acces all props autorized here
const fulltitle = A.getFullTitle(); // acces methods autorized here
const childTitle = A.children[0]?.Title; // acces child props autorized here
}
return {
create,
renderer,
A,
};
})();
export const $B = (() => {
class B {
_foo?: string = '';
get Foo() {
return this._foo + 'foo';
}
constructor(data: Partial<B> = {}) {
Object.assign(this, data);
}
}
function create(data?: Partial<B>) {
return new B(data);
}
function renderer(B: B) {}
return {
create,
renderer,
B,
};
})();
// API
//#2 Partial props only (omit methods,getter,setter) for a higth level API !
$A.create({ Title: '' }); // should not visible and lint error !
$A.create({ getFullTitle: () => '' }); // should not visible and lint error !
// want allow only this structure for higth API
$A.create({
_title: '',
_uid: '',
B: $B.create(),
children: [$A.create({ _title: '', _uid: '' }), $A.create({ _title: '', _uid: '' })],
});
我想要的是内部function renderer(A: A) {
能够使用所有公共道具方法,getter,setter。并且里面function create(data?: Partial<A>)
只允许部分数据(没有getter,setter,methods)。
所以我想要一个技巧来在这里只获得黄色道具,当我使用时create()
我尝试了许多没有成功的场景,总是在某个地方撞墙!如果您有其他方式来构建它?谢谢