#Addition of values of two union types

31 messages · Page 1 of 1 (latest)

faint ivy
#

In typescript, is it possible to create a new union type from all the possible results of the addition of two union types? The idea would be like this:

type T1 = 0 | 1 | 2;
type T2 = 10 | 20;
type T3 = T1 + T2; // same as type T3 = 10 | 11 | 12 | 20 | 21 | 22

My goal is to create a new Map() with a key that accepts [T1, T2] but since maps don't work with arrays as keys, I need to encode it first by combining the two types into some serialized form.

jaunty magnet
#

it's possible, but not easily

#

ts doesn't really do arithmatic on types

#

it'd probably be easier to just use a string serialization

faint ivy
#

How do you serialize it while still maintaining the strict typing

#

Is that possible

#

Hmm maybe it's more practical to do Map<T1, Map<T2, V>>

#

Problem with maps in general is you can't assure the compiler that the key will return a value even if you filled up the map with all possible keys

jaunty magnet
#

you could use a template type

jaunty magnet
faint ivy
#

TIL record types exist

#

Whats the difference between Record<ColorIndex, string> and { [i in ColorIndex]: string }

#

Or is that just the same thing

jaunty magnet
#

Record is a utility type that is just the mapped type you wrote

fallen rapidsBOT
#
type Record<K extends keyof any, T> = {
    [P in K]: T;
};
faint ivy
#
export const ColorIndices = [1, -1, 2, -2, 4, -4];
export type Rotation = [ColorIndex, -1 | 1];

export const rotationMatrices: Record<
    Rotation[0],
    Record<Rotation[1], THREE.Matrix4>>= {
    1: {
        1: createRotationMatrix([1, 1]),
        [-1]: createRotationMatrix([1, -1]),
    },
    [-1]: {
        1: createRotationMatrix([-1, -1]),
        [-1]: createRotationMatrix([-1, -1]),
    },
    2: {
        1: createRotationMatrix([2, 1]),
        [-1]: createRotationMatrix([2, -1]),
    },
    [-2]: {
        1: createRotationMatrix([-2, -1]),
        [-1]: createRotationMatrix([-2, -1]),
    },
    4: {
        1: createRotationMatrix([4, 1]),
        [-1]: createRotationMatrix([4, -1]),
    },
    [-4]: {
        1: createRotationMatrix([-4, -1]),
        [-1]: createRotationMatrix([-4, -1]),
    },
};

This is what I was trying to create but without hardcoding it all

#

But now that I look at it

#

Some sort of memoization would probably be better

#

Using a map

#

Would be typesafe too as long as I call the createRotationMatrix function if the map.get().get() returns undefined

jaunty magnet
#

btw if you don't necessarily have that Rotation as an input, you could use template types to flatten the structure as mentoined before

faint ivy
#

Ohh

#

Templates seem useful

#

Might be able to combine that with the memoization strategy I mentioned

#

Ok yeah they're OP

#

This code would've been a lot more cluttered without templates

faint ivy
#

My bad I forgot to resolve

#

!resolved

jaunty magnet
faint ivy
#

True