Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript strict class / interface

I use TypeScript version 2.3.4. I want to write a function that accepts an object that must have specified fields. But this object should not contain any other fields. How can I achieve this?

Now this works only if I define object inline. But if I use another object with extra fields - the compiler will allow it. What is totally wrong.

Example:

function foo(arg: { a: string }) { // there is tons of fields actually
  // ...
}

foo ({a: "qwerty"}); // No Error - ok

foo ({a: "qwerty", b: 123}); // Error - ok

let bar = {
  a: "qwerty",
  b: 123
};

foo (bar); // No Error - NOT OK !!!

The same code can be writed with interfaces, classes, type declarations - it's the same problem.

Now I have to extract the fields from the object manually to make sure that there are no extra fields. But I can't spread this solution on ~1000 functions (I really need this) all over the code - it's too messy. I creating API wrapper and I need to ensure that there are no additional or wrong fields passed to the server.

like image 655
Harry Burns Avatar asked Jun 20 '17 06:06

Harry Burns


2 Answers

The feature you are asking for is known as "exact types".
It's being considered, that is, neither rejected nor accepted, and the discussion still goes on.

like image 65
artem Avatar answered Oct 12 '22 03:10

artem


This is how it works by design and I'm not sure you can work this around. See the docs for more info.

What you also do wrong - you cannot be 100% sure about what's sent to the server. As long as browser does not know anything about TS, some library can inject into any request whatever it needs with e.g. by overwriting XmlHttpRequest methods (this is what e.g. at least angular's zone.js does).

Another way to easily break your intentions is as simple as using <any> in front of any parameter you pass.

TypeScript is intended to improve your development process but I don't think it can be used for the needs like yours. This is usually covered by writing the proper tests.

like image 43
smnbbrv Avatar answered Oct 12 '22 03:10

smnbbrv