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.
To cast something in TypeScript, we use the as keywords. For this example, we need to cast the text variable to a string, so TypeScript will let us use length : let text:unknown = "string"; let value = (text as string).
JavaScript doesn't have a concept of type casting because variables have dynamic types. However, every variable in TypeScript has a type. Type castings allow you to convert a variable from one type to another. In TypeScript, you can use the as keyword or <> operator for type castings.
How do I cast objects in TypeScript? If we want to cast the object to string data types by using toString() method we can change the object type to a string data type. We can also cast the object type to jsonby using json. parse() method we can get only the plain objects and it not used on the class object.
interface RunOptions { program:string; commandline:string[]|string|(()=>string); } //commandline as string var options:RunOptions = {program:"test1",commandline:"Hello"}; console. log(options. commandline) //commandline as a string array options = {program:"test1",commandline:["Hello","World"]}; console.
Interfaces don't exist at runtime. Your best option would be delete unwanted properties yourself or create a copy of the object with the properties you need.
For example you can use a method like this (method copied from this answer):
function pick<T, K extends keyof T>(obj: T, ...keys: K[]): Pick<T, K> {
const copy = {} as Pick<T, K>;
keys.forEach(key => copy[key] = obj[key]);
return copy;
}
const a = { a: 1, b: '2' };
let copy : A = pick(a, "a");
console.log(copy);
Basically your question boils down to the problem of getting all properties of the interface as an array of strings and then make an copy of the object containing only those properties. Making a copy of object is pretty simple and there are tons of examples out there. But the first issue is much harder to tackle.
As far as I know the only way to get this done "now" is to use custom transformers for typescript during compilation. Here is an example, but please note - this require to use typescript 2.4+ that is not yet in stable release.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With