Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

The bad convert is actually wrong. It should be refactored to an equality check and throw an error if account kind is not "dc". The compiler is correct and its not a good idea to work around this issue.


No, the point of the function is to convert the type. It doesn't need to check anything, it just forcibly converts any argument to DC.

The compiler isn't complaining because the conversion isn't valid, it's complaining because it doesn't know that the string "dc" should be narrowed down to a literal type, and so it's kept it as broad as possible. Using `satisfies` lets it understand that it needs to do narrowing here.

In fairness I don't think this is the best case for `satisfies`, and some return type annotations would probably work a lot better here, and be clearer to read.


Absolutely. It's contrived example. If you control the API, you'd be better to rewrite it:

   type Current = { amps: number; };
   type Ac = { kind: "ac" } & Current;
   type Dc = { kind: "dc" } & current;
   const currentToDc = (c: Current): Dc => ...
   const acToDc = (c: Ac): Dc => ...
And it would flow more naturally. Or define a CurrentKind and include it in current if you don't need to handle the scalar. There are plenty of better ways. That's also something that you can become accustomed to and recognize when you have a weak API.

I'm not really trying to make a case for `satifies`, but it can be handy and clean in some circumstances, especially when you're constrained by a third-party API.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: