Issue
I'd like to ask, is it possible to declare an array of unique types from union of those types?
I have this type Value:
type Value = string | number
Then I created type Values like this:
type Values = Value[]
but that creates a type:
type Values = (string|number)[]
but how can I achieve this from the type Value?
type Values = string[] | number[]
Because basically I have a function that renders checkbox-es for table filters. That checkbox will always have either string or number as a value.
Then when you click on a checkbox, it adds that value to an array. For example, you have a column firstName and you add two names to that filter. It then becomes an array of string or array of number: string[] | number[] which would represent my type Values.
So is there a way to create type Values from type Value?
I created this sample sandbox just to compare those types.
Thanks for any input!
Solution
I would choose of restricted templating
type Values<T extends string | number> = T[];
const myArr: Values<string> = [
'foo',
'bar',
];
const myArr2: Values<number> = [
1,
2,
];
Or use overloaded types (let typescript decide the type depending on what's inside of the array)
type ValueTypeA = string[];
type ValueTypeB = number[];
type Values = ValueTypeA | ValueTypeB;
const myArr: Values = [
'foo',
'bar',
];
const myArr2: Values = [
1,
2,
];
Answered By - Orelsanpls
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.