3 ms·
Soft disagree with 3. unknown might be better than any but then the typechecker isn't going to let you read any fields from the object, even if you are using a
by paxys 6y ago
Soft disagree with 3. unknown might be better than any but then the typechecker isn't going to let you read any fields from the object, even if you are using a null check. And the given example is weird because you don't need to add a type annotation there at all. The problem really is that TypeScript doesn't have an "unknown deserialized JSON" type.
For #7, in a lot of (most?) cases, the name of a generic isn't meant to be descriptive. I'd argue that functions that expect it to be are doing it wrong. If I have a `function reverseArray<T>(arr: T[])`, the point of T is that it can be anything. Saying `reverseArray<ArrayTypeToBeReversed>` serves no purpose.
TypeScript also really, really needs to have a strict typechecking mode. Yes I know the "it compiles to raw JS" arguments, but it could easily add extra checks in the JS code (basically what example #4 shows).
- horsawlarway 6y agoDisagree with you on 3. 'unknown' is handy to prevent 'any's from leaking into the codebase. It's very easy to accidentally assign an 'any' to another variable and then return it, or to accidentally read a property off of it before ensuring it exists. Unknown is basically asking the dev to confirm the choice (ideally through a typeguard, but also with a simple cast). And if you're using a typeguard, just define the argument as 'any' ex - type AType = { c: string } let a: unknown = { c: 'test', } if (isAType(a)) { console.log(a.c) // no type errors! } function isAType(a: any): a is AType { return typeof a.c == 'string' }