I've been writing in TypeScript for about a year or so now, and I've come across a nice project on Github written in Rust which I'd like to wrap in TypeScript. I've never programmed in Rust but I do have experience in C . I believe my question in the title is clear enough. Is a struct in Rust kind of like an interface in TypeScript?
CodePudding user response:
Is a struct in Rust kind of like an interface in TypeScript?
Kind of, but no.
A TypeScript interface declares what members an object must have in order to satisfy the interface, but the object can have more members. It is possible for one JavaScript object to satisfy multiple TypeScript interfaces of wildly different shapes, simply by having all of the stuff needed for those interfaces at the same time.
In Rust, a struct is the definition of a composite type. Every value of that type has exactly the members declared in the struct's definition -- no more, no less.
It would be a better analogy to say that a TypeScript interface is like a Rust trait. Both declare a required set of "stuff" needed to satisfy the interface/trait, and multiple traits can be implemented on the same struct. However, this is still not a 100% accurate analogy as traits cannot declare fields (data members / properties), only functions, constants, and types.
Also, note that TypeScript interfaces are structural, not nominal. This means that two TypeScript interfaces with the exact same structure are effectively interchangeable despite having different names; you can implicitly "convert" a variable from one such interface to another, and no cast is required to do so. In Rust, two structs with identically-declared fields are not interchangeable in this way, and neither does this apply to traits with identical contents. (If it did, marker traits like Copy
, Send
, Sync
, etc. could not exist because they would be implicitly implemented on every type!)
What is the TypeScript equivalent of a Rust struct?
There isn't really a good equivalent. Structs define what fields a value has, but in JavaScript/TypeScript objects don't have an immutable shape -- they can always be extended with new stuff at any time, so JavaScript doesn't need the concept of a "struct" per se. Dynamically-typed languages generally don't have a need for field declarations; this is something that you tend to only see with statically-typed languages.
TypeScript brings some amount of static typing to the dynamism of JavaScript, but the dynamism is still there even in TypeScript. TypeScript is not so much "statically-typed JavaScript" as it is "JavaScript with some type checking sprinkled in."