2

I have a situation where I have an array of objects containing a value that must be a key of some other type. The simplest version is something like this:

interface Object<T> {
    name: keyof T
}

type ArrayOfObjects<T> = Object<T>[];


function f<T>(arr: ArrayOfObjects<T>){
    //...
}

This is really nice because it allows me to check that any values I pass in the object array have a valid "name" that corresponds to a key of type T.

Is there any way to also ensure that every key of type T is included in at least one object in the array arr as the value corresponding to name?

ICW
  • 4,875
  • 5
  • 27
  • 33
  • 2
    See [this](https://tsplay.dev/Nlp0rN) for a possible approach; it's messy, but there's no direct support for "exhaustive arrays". I based this off the answer to [this question](https://stackoverflow.com/questions/55265679/enforce-that-an-array-is-exhaustive-over-a-union-type). I may close this question as a duplicate of that one. – jcalz Jul 10 '21 at 00:18
  • @jcalz This is really cool, thanks. Although, I'm not sure how to get it to work when it isn't applied to a function parameter. In my case I'm trying to check an array passed as a prop in React. Do you know if it is at least possible to do without having to check a function parameter? – ICW Jul 11 '21 at 14:44
  • I'm not sure how it works with React props. Could you modify your code to be a [mcve] suitable for dropping into a standalone IDE like the TypeScript Playground that demonstrates what your issue is? – jcalz Jul 11 '21 at 18:17
  • @jcalz https://tsplay.dev/w2K6YN It seems like it's something that should be doable since it's not that far off from your original example I think – ICW Jul 11 '21 at 18:31
  • I'd do [this](https://tsplay.dev/WK8kow) for that example; it has the same caveats with currying as before. If this works for you let me know. – jcalz Jul 12 '21 at 17:59

0 Answers0