I have the following State
shape and want to define a flattened slice
const that has the types of the state properties without needing to explicitly define/reference them again, so I would like a mapped type like MapFlatSlice
:
type State = {
fruit: {
mango: 'haden' | 'keitt';
papaya: 'sunrise' | 'strawberry';
};
colors: {
green: 10 | 20 | 30;
};
season: {
nartana: 'april' | 'may' | 'june' | 'july' | 'august';
};
};
type MapFlatSlice = {
// ...
};
const slice = {
fruit: ['mango', 'papaya'],
colors: ['green'],
season: ['nartana'],
} as const;
type S = MapFlatSlice<typeof slice>;
Where S
should be:
type S = {
mango: 'haden' | 'keitt';
papaya: 'sunrise' | 'strawberry';
green: 10 | 20 | 30;
nartana: 'april' | 'may' | 'june' | 'july' | 'august';
};
In the above example, slice
is used for something like redux's mapStateToProps
, like this:
const makeSlice = (s: Slice): (t: MapFlatSlice<typeof s>) => void => {
// ...
};
So given:
const s1 = makeSlice(slice);
Then s1
would be:
const s1 = (props: {
mango: "haden" | "keitt";
papaya: "sunrise" | "strawberry";
green: 10 | 20 | 30;
nartana: "april" | "may" | "june" | "july" | "august";
}) => {};
(where the type of props
in s1
is the same as S
from above)
So I think that MapFlatSlice
should be something like...
type MapFlatSlice<S extends { [k in keyof State]?: readonly (keyof State[k])[] }> = {
[k in keyof S]: {
[_k in S[k][number]]: ...
};
};
But I don't know how to "flatten" it, and also it doesn't work to index S[k]
with number
.
State
like this playground, or some object literalconst extract
, or was that just something you were attempting along the way? – chrisbajorinconst slice
is passed to a function that returns a function that accepts the return type of MapFlatSlice<typeof slice>. It's similar to redux mapStateToProps. I have added more details to the question to hpefully clarify what I am trying to do. – Mahesh Sundaramslice
meant to be selecting a subset of the existing properties? That is, isconst slice = {fruit: ['mango'], color: ['green'], season: [] } as const;
meant as a potential/intended input to the type? – chrisbajorinconst slice = ...
is meant as an input to the type – Mahesh SundaramState
supposed to havecolors
orcolor
as a key? Is this a typo? If so, could you fix it? If not, could you explain what's going on with the discrepancy? – jcalz