For the sake of time and simplicity, the code examples in this question are simplified.
I have a function that takes in an array of objects and for each object in that array it creates a variation of a product. Then, it returns all of the variations as an array of those variation objects.
const generateProducts = (productMockData: object[]) => {
const products = productMockData.map((mockData) => {
// create a variation of the product based on mock data
const productVariation = ...
return productVariation;
})
return [...products]
}
Here's an example of how this function is used:
const [productVariation1, productVariation2] = generateProducts([{color: 'red', price: 20}, {color: 'green', price: 100}])
In the example above, we passed in an array of two objects to the generateProducts function, so the function returns an array of exactly two variation objects.
The issue is that if you accidentally expect an array of three objects to be returned from the function, instead of two, TypeScript doesn't throw an error.
const [productVariation1, productVariation2, productVariation3] = generateProducts([{color: 'red', price: 20}, {color: 'green', price: 100}])
In this case, we expect to have three variations of a product, but there are only two, since we only passed two to the generateProducts function. Still, TypeScript doesn't throw an error.
Is there a way to get better TypeScript support for this use case?
The reason that your debuger is not trowing an error is that ists not an error... Yourself have to decide if this "interaction" is valid or not.
Your generateProducts function looks great but if you want to validate if the program is trying to have 3 variation based on 2 model object (the parameters given to the function) I think you have to fundmental choices:
1- Create a class that implements you generateProducts function and a property that will hold your array with null variables => [null,null,null] and then.
Second solution is to had your returned array has second parameter for your function =>