235 points · by alexharri · 3y ago · 154 comments
/**
* Like Object.keys, but unsound in exchange for more convenience.
*
* Casts the result of Object.keys to the known keys of an object type,
* even though JavaScript objects may contain additional keys.
*
* Only use this function when you know/control the provenance of the object
* you're iterating, and can verify it contains exactly the keys declared
* to the type system.
*
* Example:
* ```
* const o = {x: "ok", y: 10}
* o["z"] = "UNTRACKED_KEY"
* const safeKeys = Object.keys(o)
* const unsafeKeys = objectKeys(o)
* ```
* => const safeKeys: string[]
* => const unsafeKeys: ("x" | "y")[] // Missing "z"
*/
export const objectKeys = Object.keys as <T>(obj: T) => Array<keyof T>
/**
* The type of a single item in `Object.entries<T>(value: T)`.
*
* Example:
* ```
* interface T {x: string; y: number}
* type T2 = ObjectEntry<T>
* ```
* => type T2 = ["x", string] | ["y", number]
*/
export type ObjectEntry<T> = {
// Without Exclude<keyof T, undefined>, this type produces `ExpectedEntries | undefined`
// if T has any optional keys.
[K in Exclude<keyof T, undefined>]: [K, T[K]]
}[Exclude<keyof T, undefined>]
/**
* Like Object.entries, but returns a more specific type which can be less safe.
*
* Example:
* ```
* const o = {x: "ok", y: 10}
* const unsafeEntries = Object.entries(o)
* const safeEntries = objectEntries(o)
* ```
* => const unsafeEntries: [string, string | number][]
* => const safeEntries: ObjectEntry<{
* x: string;
* y: number;
* }>[]
*
* See `ObjectEntry` above.
*
* Note that Object.entries collapses all possible values into a single union
* while objectEntries results in a union of 2-tuples.
*/
export const objectEntries = Object.entries as <T>(
o: T
) => Array<ObjectEntry<T>>Reason being it's very easy for a new developer to come along and see "objectKeys" being used all over the place, and then assume it's safe to use everywhere without realizing the problem it could cause. Putting "unsafe" in the name (unsafe actually feels a little strong for me, maybe something like "lax" or something else would be better?) makes it a lot more likely that a new dev is at least going to look up the doc on the function to see why it's unsafe.
I did a quick survey of the 316 occurrences of `objectEntries` in our codebase and found very few (like 15-ish) that weren't obviously on a Record type like `Record<ThingyID, Thingy>` or a static, constant configuration object like `{ [T in Foo["type"]]: HandleFooVariant<T> }`.
- How often are you forced to interact with JS objects over ECMA6 Maps?
- How often are you not forced to use JS objects over ECMA6 Maps, but are using them anyway?
type BlockRenderers<Out> = {
[key in keyof BlockValues]: (
args: BlockRenderArgs<Out, BlockValues[key]>
) => Out | undefined
}
or something like: type Table = 'block' /* | ... ~70 other table names */
type ID<T extends Table> = `${T}:${UUID}`
type TableToRow = {
block: BlockValue
// ... ~70 other table schemas
}
type RowsById = { [T in Table as ID<T>]: TableToRow[T] }
Maps are also annoying to persist compared Record<K, V> types which just work with JSON. The majority of our code is oriented around JSON-serializable discriminated union types. In my benchmarking, transcoding to/from Map<K, V> to Record<K, V> doesn't seem worth the effort.So, we Map for in-memory only data organization and some framework stuff but most engineers tend to interact much more with persisted data and thus Record types.
Although I’m surprised there is no mention of the best solution for iterating both keys and values:
for (const [key, val] of Object.entries(obj)) { console.log(key, val) }
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
https://news.ycombinator.com/item?id=36458300
And according to the article, the issue isn't that TS doesn't realize it's the same object, it's that the object might have more keys than what is declared in your interface.
Perhaps what you meant to say is that you can directly use `val` instead of `obj[key]`.
If I need to count occurrences of each character in a string, I'm using a loop.
Edit: ah I assume you mean more like a histogram. Yeah, that's going to be less clean, e.g.
input.split('').reduce((acc, el) => ({...acc, [el]: ( acc[el] ?? 0 ) + 1 }), {});
It's a design decision which is a tradeoff, like most design decisions.
I won't mind to have instead a more succinct syntax for covariance, like `event: KeyboardShortcutEvent+`, maybe along with a similar syntax for contravariance (fewer properties).
OTOH declaring a well-typed helper function and instead of `Object.keys(x)` write some `TypedObject.keys(x)` does not seem hard to me.
This problem is much bigger. You can for example easily imagine api where you provide where clause that is converted to sql form. You may declare type to expect only certain parameters, but it won't help you at the type level as anything extra can be passed. This can be abused to extract some sensitive information.
You're forced to emulate exactness by always destructuring objects - not great.
You're forced to emulate exactness by always destructuring objects - not great.
It’s almost like using objects as enumerable maps is an anti-pattern.This is not meant as an argument against what you’re saying, because I know you were just giving an example, but I found this and thought you may find it interesting: https://www.hacklewayne.com/a-truly-strongly-typed-printf-in...
1. nominal types for classes (with correct variance/liskov substitution principles)
2. structural types for the rest
3. explicit annotation for exact structural types
This setup is brilliant.
But there are some problems with that approach, mainly that exact types would be somewhat infectious: A regular type is no longer assignable to its exact type, ie `User` is not assignable to `exact User`, so if you want to use an exact type in a function, you must accept the exact type as a parameter, which spreads to the whole call stack where that parameter is passed. Then union types don't quite work as expected anymore either.
I'm pretty happy with the status quo: Object.keys() is unsafe, so either cast your way around it and let the cast be the signal that you're doing something unsafe, or handle unexpected keys explicitly.
It’s not possible at the moment as all type information is erased at runtime of course.
import * as t from 'io-ts';
/* -------- Runtime type definitions -------- */
export const FooSchema = t.type({
someStringKey: t.string,
someNumericKey: t.number,
someLiteralKey: t.union([t.literal(1), t.literal(8675309)])
someOtherType: t.type({
anotherNumber: t.number,
yetAnotherType: BarSchema
})
})
export const BarSchema = t.type({
...
})
/* ---- Run-of-the-mill Typescript types ---- */
export type Foo = t.Typeof<typeof FooSchema>;
export type Bar = t.Typeof<typeof BarSchema>;
// Static usage
export const Baz: Foo = { someStringKey: 5 } // Compile error! Missing keys/etc
// Runtime usage
export const isFooType = (input: any): input is Foo =>
FooSchema.validate(input)
if (!isFooType(someUserInput)) return server.send(404);
You can enforce exact type shape, or just ignore excess keys, etc. It's pretty handy, and saves me so much work maintaining two type systems, a static one for development and a runtime one for production.All of the typical caveats apply: consider runtime performance cost, recognize that deep/nuanced types will require a deeper/nuanced understanding of io-ts, there are limitations, alternative libraries with different tradeoffs, and so on.
I like it. :)
Of course, that only works if we know the type statically just like in the example of the post. But that is exactly the usecase that is needed in this example and then the type-errors are gone.
https://github.com/Microsoft/TypeScript/wiki/TypeScript-Desi...
Edit:
Non-goals:
…
5. Add or rely on run-time type information in programs, or emit different code based on the results of the type system. Instead, encourage programming patterns that do not require run-time metadata.Fetch returns “any” meaning you can’t trust the data you received is actually the data you expected. Bugs from this mismatch will be many lines away (on first use) and more difficult to find. Because of this “goal of the language” you cited, there’s no built-in way to validate any data at runtime. In nearly any other typed language I have some deserialization mechanism. Not so in Typescript!
This decision led to more bugs in our codebase than any other. The compiler actively lies to you about the types you’ll have at runtime. The only solutions are codegen or writing validators to poorly approximate what Typescript should give us for free.
The correct type for values you don’t know the type of (like the response of an API call) is “unknown”.
TypeScript does not provide the facilities you describe because there is not a one-size-fits-all solution to the cases that are possible and common in JavaScript.
It is left to the developer to decide how to validate unknown data at the boundaries of the API.
There are third party libraries that facilitate this in different ways with different trade-offs.
The compiler actively lies to you about the types you’ll have at runtime.
I find this to be rare if you are using strict mode with proper TypeScript definition files for your platform and dependencies. Usually the lie is in your own code or bad dependencies when an “unknown” type (including “any”) is cast to a concrete type without being validated. In nearly any other typed language I have some deserialization mechanism.
Could you provide examples? I either don’t understand or I disagree.Predicates are the most performant but won't give you any indication on why it failed (ie. some nested field was null but was expected to be number etc).
Refutations is great sweet spot as it's fast while giving information about error.
Assertions are slow, but more often than not you don't care.
You can map between any of them, but it doesn't make much sense for mapping ie. assertion to predicate as you'd be paying cost for nested try/catch while dropping error information.
Refutation is great base for all 3.
Regarding runtime type checking, if you were to write something that can handle the total space of possible TS types, you would end up with incredibly complex machinery. It would be hard to make it perform, both in terms of speed and bundle size, and it would be hard to predict. I think Zod or perhaps https://arktype.io/ which target a reasonable subset are the only way to go.
The downside is the underlying types tend to be more complex when viewed in your IDE, but I think it's worth it.
Types are inferred from the schema though personally I like to handwrite types as well to sense check that the schema describes the type I think it does
I'm not sure if there is a) any "programming pattern" that can avoid this without other drawbacks and b) if there is any problem with emitting different code based on the types (at compiletime).
I suppose it could lead to breaking behaviour if the typesystem is changed, since it now can impact runtime code. Personally, I think this would be more than worth it, but maybe the typescript team has a different opinion or other reason.
Typescript only got official ECMAScript decorator support in the recent v5. ECMAScript decorators only got to stage 3 in April ‘22.
But decorator syntax is just a kind of syntax sugar over passing a function through another function, and you can do that today to achieve runtime type information (see zod etc). Zod could be rewritten using decorator syntax and still be “just JavaScript” while providing compile-time type support.
The distinction being that supporting ECMAScript features is a goal for Typescript, but they were perhaps too aggressive early on in investing in decorators and the Reflect Metadata API. They had the wisdom to put these behind “experimental” flags, but I think they got quite popular within the typescript community due to the early adoption of both Typescript and both those features by Angular, which was really the only major lib using TS for quite some time.
I'm always bothered by the idea that product types can be "more" than, but never "less" than, the type they are assignable to (contra-variance). For sum types it seems to be the opposite (co-variance), so structural typing is easier.
Which reminds me of an idea I've had for a while regarding object oriented inheritance. Why is inheritance always approached in a contra-variant manner? I have frequently wished that inheritance could be conceptualized as a narrowing, rather than expansion, of type. For example, consider an "Animal" object class, which has a "numLegs" attribute. Then "Dog" could inherit from "Animal" by having exactly 4 legs, as a special case.
I'm not sure whether this concept has been implemented in any language, but I've encountered situations where it would have been the perfect way to model entities, frequently enough, that I believe it could be very useful.
trait Foo{
class Bar
def doNothing(b: Bar){}
}
val f1 = new Foo{}
val b1 = new f1.Bar()
val f2 = new Foo{}
val b2 = new f2.Bar()
f1.doNothing(b1) //fine
f1.doNothing(b2) //won't compile
Applying the same idea to TypeScript, you could imagine using 'keyof' on values instead of types. So instead of keys<T extends object>(o: T): (keyof T)[];
it would be something like keys(o: object): (keyof o)[];
And the keys returned for an object would only let you index into that specific object, not any other object even if it had the same type.[1] https://wheaties.github.io/Presentations/Scala-Dep-Types/dep...
Row-polymorphism instead of structural subtyping.
The idea is that instead of treating `Record<,>` as parameterized by two ordinary types, you parameterize it with a single type-level collection of key-value pairs, and then write functions which are generic over parts of that collection. So the equivalent of a typescript function that works fine over open records would look something like this `<Rest>(obj: { SomeRow, Rest }) => { SomeRow, Rest }`, whereas `(obj: { SomeRow }) => { SomeRow }` says you can't have any extra entries and `<Rest>(obj: { SomeRow, Rest }) => { SomeRow }` says you can have extra entries but they're getting thrown out.
This also lets you reuse machinery between records and sums more easily, since sums are also realizations of rows.
Purescript and OCaml have good row type support. You can also sort of hack it together in typescript if you're very very careful, but I wouldn't recommend it.
In Delphi you can do this:
type
TAnimal = class abstract
public
class function NumLegs(): integer; virtual; abstract;
end;
TDog = class(TAnimal)
protected
class function NumLegs(): integer; override;
end;
{ TDog }
class function TDog.NumLegs: integer;
begin
result := 4;
end;
var
d: TDog;
begin
WriteLn(TDog.NumLegs); // 4
d := TDog.Create;
WriteLn(d.NumLegs); // 4
end.
I've used this several times to good effect. Were you thinking of something else? If so, could you expand a bit? const realkey = key as any as <type>
And call it a day. I'm 100% certain I've typed fewer characters of that pattern than that blog post.For example: `const user = { name: 'Bob', city: 'Reykjavík' }; saveUser(user)` is allowed because of structural typing. But `const user: User = { name: 'Bob', city: 'Reykjavík' }` throws a compile error; you're telling that you're specifying a `User`, but the value you give is not (just) a `User`.
function validateUser(user: User) {
let error = "";
for (const key of Object.keys(user)) {
const validate = validators[key];
error ||= validate(user[key]); // <-- only first error is assigned
}
return error;
}
// instead I would put something like this..
error += validate(user[key])But it doesn't do this =(
type FrozenObject<T> = { readonly [K in keyof T]: T[K] } & { readonly [key: string]: unknown };
const x = { foo: 1, bar: "hello" }
x["baz"] = "blah"
const frozen = Object.freeze(x) as FrozenObject<typeof x>
const baz = frozen.baz // No autocomplete for 'baz', but no error either function parse(input: string): string, throws SyntaxError {}
However in JavaScript we can not guarantee that when calling `parse` the only error you might get is the error that this function throws. So there is no point in adding type annotationPersonally, I hate typescript. So much redundancy. It's not insanely awful, but just awful and unnecessary enough (except large corporate projects with significant developer churn) that it's a pet peeve of mine.
"Hey, let's just write the same thing 4 times so you know it's a string! Because quotation marks aren't clear enough! Yay!!" "I must redundantly ensure you know this number is a number! Even though you can easily convert it to one if you need to, and move on! Yay"
I'm bummed that it is becoming so common and popular in the industry.
`const foo = "bar"` makes foo a constant string "bar"
Where are you having the redundancy?
I can think of one place that causes me problems, which is typing and destructuring at the same time in function parameters. But there's no type redundancy there, the redundancy is having to write variable names twice.
I don't get where you're coming from. Yeah you can easily convert something to a number[1], so isn't it a good idea to force a dev to do that easy conversion by emitting a compile-time error if they don't? Because if they don't, and the value doesn't get coerced correctly, then the code blows up at runtime.
[1] Except when you can't and you get NaN
I dont follow. Can you provide an example of what you mean?
Object.keys returns an array of strings. Non-ennumerable properties and Symbol-keyed properties aren't included (on the off chance that's even relevant). That's it. It's not rocket science.
This article is complete nonsense. "What if there's no e-mail validator!", then write one? Or don't try and validate an e-mail? Like ?????? How do you not know what properties the object you're validating can have? Is this seriously how these devs operate? Just write some code with no idea what data is coming into it and no desire whatsoever to iron that out before continuing?
6 months with a dynamic language, if you actually bother to learn how to code, and you'll start reading and writing code in such a way that it's blatantly obvious what every type is. I cringe when I see people say stuff like "Typescript forces you to think about types!", in practice it's the complete opposite. There's a basically perfect correlation between devs I've worked with that like TS and those that have no idea what's going on with their code and constantly need to bug the other developers for help.
I was gobsmacked the first time I looked over a TS dev's shoulder and saw them trying to make changes without actually reading any of the code first. Zero idea what variable is defined where or what it holds, nah fuck that, just jump to line 148 and hover over a couple of things to try and pick up the thread from there, she'll be right.
> . I cringe when I see people say stuff like "Typescript forces you to think about types!", in practice it's the complete opposite … make changes without actually reading any of the code first. Zero idea what variable is defined where or what it holds, nah fuck that, just jump to line 148 and hover over a couple of things to try and pick up the thread from there, she'll be right.
Why should you need to do anything else than that? If TS enables better hinting, and you can just make a change without having to sit down and digest and entire codebase first, then why not enjoy taking advantage of that? How is that not desirable? Why make things more complicated for yourself than they need to be, when you can let your tools do that work for you?
This would only be true for very simple code written in a top-down manner. For library code, you dont know how what code will call the library.
It has little to do with structural typing per se; you would have the same behaviour with nominal classes* and inheritance.
* this is likely why OOP languages have _final_ classes
It is a logical but perhaps counter-intuitive consequence of supporting reflection in a statically typed language. Most languages avoid the issue by either not supporting reflection or by having reflection be untyped (eg returning all members as “object” and let the client cast to the appropriate type). Typescript tries to support type-safe reflection, but this means the types have to be wider than you would intuitively expect, in order to take subtypes into account.
People using TypeScript write blog on why Typescript can't even type `Object.Keys`. Someone who only spents time in C++, Go, Java, or Rust would be surprised at this.
Types in TypeScript are like Cheese in Cheeseburger, there is a slice of it but the meat is entirely made up of something else.
Here's my question to you why is this problem non-existent in c++/Java/go/rust?
After 1 year of Vanilla JS you will know all the types by heart.
All the necessary static type analysis will be happening automatically in your brain.
No cluttered type syntax and linter wars needed.
Tell me you’ve never developed large projects on a team without telling me…
That's exactly the point: nobody wants to do this in their head, and humans are far worse and less consistent about these kinds of computations than machines. Plus, as the size of a codebase grows, the chance that you have it all in your head approaches 0%.
Also, I'm not sure what "linter wars" have to do with TS?
Sure I say go for it for those super galactic world changing giga projects but most simply aren't that.
A project with well organized, clean code without a lot of junk will be a small, easily overseeable project, for a long long while.
Also, when multiple people are working on the same code, it's nice that they all are forced to spell things the same way...
For my little site I needed an input element with type=file.
So I was getting started, with TypeScript and all, like the swaggest of web developers.
Came the moment for the actual file input:
TypeScript REFUSED to accept the input element's type as "HTMLInputElement" when that is literally its type.
After TypeScript eating up about 1 hour or so of my time, I decided to get rid of that piece of sh*t for squiggly underlining all my code in Red simply because it's too retarded to understand it.
Any of the TypeScript lovers care to explain?
Needless to say, I ultimately went about doing what I wanted in 5 minutes in VanillaJS and was happy ever after.
Call me again when TypeScript does its job correctly.
As to your problem: Use ˋ... as HTMLInputElementˋ if Typescript wasn't able to narrow your type sufficiently, or you believe that the value of typing this case isn't worth the effort. This should be somewhat rare.
Use ˋ... as unknown as HTMLInputElementˋ, if your idea of the variable is completely different from Typescript. But at that point you likely _have_ made a mistake somewhere.
Use ˋ...: anyˋ if you want to completely turn off checking. In most projects, this has to be explicitly specified for each parameter and declaration.
It gets more verbose, the more unsafe your code is.
Enabling Typescript on an existing, untyped project is going to be rough to start. You'll need to gradually increase the strictness levels and perhaps work on typing one module at a time. With an entirely new project, start with maximum strictness, and things will come together much easier. You might need to learn to do things in new ways to make it easier to work with TS, but that doesn't mean it's wrong.
Certainly, 1 hour to attempt to use any new technology is way too little time. I'd say a minimum of a week of honest effort with a new toy project is warranted before deciding whether it's not for you.
But I doubt you’ll be able to keep up with contributions from three other devs to a massive codebase.
Typescript makes it easier to understand what’s going on at a glance (or a hover, or a ctrl+click) - I’m fine with loosey goosey JavaScript for a solo project, or even a two person collaboration, but for a big team effort? I’m gonna need those strict typings to help keep everyone’s contributions consistent.