Open EdwardZZZ opened 1 year ago
enum E { a = 'a', b = 'b', } class A { name: string = 'Zhangsan'; pw: E = E.a; sports: string[] = ['swimming', 'running']; } /** * is/has fn? * @returns */ function Checker<T extends { [key: string]: any }>(obj: T): { [P in keyof T]: { is: T & Record<T[P], boolean>; has: T[P] extends Array<infer U extends string> ? Record<U, boolean> : never } } { return new Proxy<T>(obj, { get(target: T, field: string) { return new Proxy(target, { get(target: T, type: string) { return new Proxy(target, { get(target: T, val: string) { const v = obj[field]; if (v === undefined) return false; if (type === 'is') return val === v; if (type === 'has') return v.indexOf(val) > -1; return false; }, }); }, }); }, }); } const a = new A(); console.log(a, Reflect.ownKeys(a)); console.log(Checker(a).name.is.Zhangsan); console.log(Checker(a).name.is.Lisi); console.log(Checker(a).pw.is.a); console.log(Checker(a).pw.is.c); console.log(Checker(a).pw.has.a); console.log(Checker(a).sports.has.swimming);