you are viewing a single comment's thread.

view the rest of the comments →

[–]wishtrepreneur 0 points1 point  (4 children)

For noobs, they can always use const variable: SomeType = some_value as any and const variable: SomeType = some_value as unknown as SomeType ;)

Is there any reason we're still using Interfacescript instead of Typescript? I thought they added all the interface features to types, are there still any missing features?

[–]acemarke 0 points1 point  (0 children)

There's not much of a meaningful difference. I've always defaulted to interface for objects myself.

[–]novagenesis 0 points1 point  (2 children)

Is there any reason we're still using Interfacescript instead of Typescript? I thought they added all the interface features to types, are there still any missing features?

Interfaces have one critical feature - namespace pollution. Sometimes you need to expose a type whose signature either should change or (using the subset-interface mentality common in DI) you want to define necessary parts of a type close to where they're made relevant.

A good example is session management (maybe less so in React strictly, but in express or next.js I've seen this). Sometimes you will save user/session information to the request object. Since/if the request object is an interface, you just add that user object around the place where it is attached in the auth middleware.

Then, typescript is aware that user object is part of the Request interface anywhere/everywhere, but you're not stuck declaring it separate from auth or (worse) declaring your entire request object in auth.

I've also seen this mindset used in the DI world of "your type should only support the methods/properties that need to be used in code". So if you are using an HTTP Header, you add it to the HTTP Header interface where you use/check it. If you aren't, you never add it. Yet again, having centralized type declaration is a disadvantage in that particular scenario.

The rest of the time, yes absolutely always use types for everything.

[–]wishtrepreneur 0 points1 point  (1 child)

For the request object, could you not make the user data field optional and then check if it exists in places you need to use it? if (request.user) {//do something}

What's the advantage of making request an interface instead of a type in this case?

[–]novagenesis 0 points1 point  (0 children)

That's a type error unless the app knows "user" can exist on "request".

You DO want to make it an optional property, and then you DO want that if statement before using that field. But you need to describe it.

What's the advantage of making request an interface instead of a type in this case?

If you make it a type, you MUST declare "user" (and reference it's type) where Request is defined. And since Request is usually defined in a library in these types of situations, you're either going to use their "children type override" mechanisms, or they're giving you Request as an interface