Suppose there is an interface
interface A {
a: number;
}
and currently I have a raw object
const a = { a: 1, b: '2' };
I expect a way to get x to be { a: 1 }, which contains only members defined in interface.
This can be achieved through creating an empty {} and looping over and filling in all A's members, but considering interface members and object's redundant fields can be up to dozens, it is not practical to do so.
I tried
let x = <A> a; // or let x = a as A;
console.log((x as any).b); // still exist
I also looked up in lodash and found keys and pick, but these are targeted for class instance instead of interface.
atoAand with typescript editors you can access only to members ofAbut the real object is always of typea. Because ts type erasure implies that objects are of typeObjectat runtime you see the wholea. If you want another object you have to copy its properties (like pick solution suggests). Instead if you want a compile time check useAand don't worry about what the real object is.interface B { b: string; }. You can treat the objectaas an object of type bothAandB:let x: A = ayou can access members ofAorlet x: B = ayou can access members ofB. The objectais of type Object which is the only one existing in javascript.