1

I have a situation where i defined a generic type

type ItemAndArray<T> = {
    item: T,
    array: T[]
}

i want to define another type as an array of items from this type

type ArrayOfItemAndArray = (ItemAndArray<any>)[]

but this definition doesn't really encapsulate my type restrictions well since this code compiles:

const val: ArrayOfItemAndArray = [
    {
        item: 'string',
        array: [1, 2, 3] // shouldn't compile since string and number are not the same type
    }
]

if i was writing in a language like java i would use something like

    public class ItemAndArray<T> {
        public T item;
        public T[] array;

        public ItemAndArray(T item, T[] array) {
            this.item = item;
            this.array = array;
        }
    }

and i would use wildcard generic to specify the array type

    ItemAndArray<?>[] val = {new ItemAndArray<String>("string", new Integer[]{1,2,3})}; // doesn't compile since Integer array should be string array

does anyone have an idea on how to specify this type?

1
  • Wildcard generics in Java are a form of existentially quantified generics, which TypeScript doesn't have direct support for. You can emulate existentials in TypeScript with a control inversion, like this. See the other answers for details. Commented Apr 20, 2022 at 18:13

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.