array values subset
See use cases.
Allow users to type keys based of an array - but do not force users to put all the keys from the array values, just a subset of the values present in the array.
Simple example, this does not compile, but I want this to compile:
const Events = <const>[
'bar',
'foo',
];
type MyEvents = typeof Events[number];
export interface Disco {
elmo: {
[key in MyEvents]: true
}
}
const x: Disco = { // compiles
elmo: {
bar: true,
foo: true
}
};
const y: Disco = { // does not compile, because key y.elmo.foo is missing
elmo: {
bar: true,
}
};
const z: Disco = { // does not compile, because key y.elmo.bar is missing
elmo: {
foo: true,
}
};
The reason the above does not compile is because my objects do not implement all these keys:
'foo'
'bar'
they only implement 1 of them. But I want to tell TS that as long as it's a subset of the above list, that it's fine.
I tried using key in Partial<MyEvents> but that didn't work (even tho it would be nice if it did?)
Partial could work for array values not just objects? idk.
Note this same problem occurs when just using a type instead of an array:
type MyEvents = 'bar' |'foo'
export interface Disco {
elmo: {
[key in MyEvents]: true // still requires elmo to have both foo and bar props
}
}
My suggestion meets these guidelines:
This is already a feature (which is how Partial is implemented). Use this:
export interface Disco {
elmo: {
[key in MyEvents]?: true // notice the ? modifier
}
}
At the risk of being banished to the chillaxation zone a second time, I'd like to gently point out that Stack Overflow could be a more appropriate place for issues like this where you're not sure if a feature exists or not. Now please excuse me while I cower behind these trees... 🌳😨🌳
Does the feature have a name? Very hard to find documentation on it
Maybe "optional property modifier for mapped types"? It's documented here but it doesn't say the words "optional modifier". It does show how Partial is defined, though.
You an map the union MyEvents to an object type using a conditional type:
type MyEvents = 'foo' | 'bar';
type UnionToRecord<T> = T extends keyof any ? Record<T, true> : never;
interface Disco {
elmo: UnionToRecord<MyEvents>;
}
This issue has been marked as 'Question' and has seen no recent activity. It has been automatically closed for house-keeping purposes. If you're still waiting on a response, questions are usually better suited to stackoverflow.
Most helpful comment
This is already a feature (which is how
Partialis implemented). Use this:At the risk of being banished to the chillaxation zone a second time, I'd like to gently point out that Stack Overflow could be a more appropriate place for issues like this where you're not sure if a feature exists or not. Now please excuse me while I cower behind these trees... 🌳😨🌳