Posts

Showing posts with the label typescript

TypeScript: Turn an Array of Values into a Type Union

I found the answer I was looking for here: https://dev.to/shakyshane/2-ways-to-create-a-union-from-an-array-in-typescript-1kd6 I wasn't sure that it would be possible. In fact, it turns out that the solution is far more impressive than I expected. What follows cuts to the core part of the article that I need solved my particular problem. Problem I want to have an object type with specific keys and I want a static array of those keys, but I don't want to have the same list of keys written out twice in case I mistakenly make them differ in the future type K = "a" | "b" | "c"; type O = Record<K, V>; const keys: K[] = ["a","b","c"]; I want to be sure that 'keys' contains every member of type 'K' exactly once and vice-versa. I want to use 'keys' to build an object of type 'O', so I can't just rely on using 'Object.keys' on an ...

The TypeScript "extends" Keyword Doesn't Extend Types

I was looking through the built in TypeScript definition file "lib.es5.d.ts" and found the definition "Pick". //From T pick a set of properties K type Pick<T, K extends keyof T> = {     [P in K]: T[P]; }; In more words: Pick<T,K> is a new type of object whose keys are the set K , which has to be a subset of the keys in T . But when I tried to understand what it was from the code itself, I had some trouble, and the source of that trouble is simply the extends  keyword. We usually use ' A extends B ' to mean  A  has all the keys in  B  and maybe some more, which the English also suggests. But in reality  K must be a subset of T 's keys. What is going on? What is a Type? A type is a set of values based on some rule. e.g. Colour = { red orange yellow ... } If A is a subtype of B, values that match A are a subset of values that match B. The definition of the subtype therefore has to be a narrower ve...