UI, Pure and Simple (By Christian Johansen) [video]
youtube.com1 pointsby weavejester0 comments
type Assoc<M extends object, K extends string, V> =
Omit<M, K> & Record<K, V>;
function assoc<M extends object, K extends string, V>(
m: M, k: K, v: V): Assoc<M, K, V> {
return { ...m, [k]: v } as Assoc<M, K, V>;
}
(Note that we need to perform an explicit cast in order to inform TypeScript of the type of the key.) type Simplify<T> = {[K in keyof T]: T[K]} & {};
type Assoc<M extends object, K extends string, V> =
Simplify<Omit<M, K> & Record<K, V>>;
function assoc<M extends object, K extends string, V>(
m: M, k: K, v: V): Assoc<M, K, V> {
return { ...m, [k]: v } as Assoc<M, K, V>;
}
(The empty `& {}` intersection forces normalization, providing a cleaner reported type.) type Simplify<T> = {[K in keyof T]: T[K]} & {};
type Assoc<M extends object, K extends string, V> =
Simplify<M & Record<K, V>>;
type AssocValue<M extends object, K extends string, V> =
K extends keyof M ? (V extends M[K] ? V : never) : V;
function assoc<M extends object, K extends string, V>(
m: M, k: K, v: AssocValue<M, K, V>): Assoc<M, K, V> {
return { ...m, [k]: v } as Assoc<M, K, V>;
}
So this is possible to type in TypeScript (to its credit), but is it "trivial"? And is this type signature significantly less complex than one might find in Haskell? (let [m* (assoc m :number 3)]
(:number m*))
We can see that the return type of this expression is obviously an integer, but what is the type of m*? How do we type m* such that (:number m*) can be inferred to be an integer by the compiler?