I am experimenting with TypeScript for this project
type ArrayOrSingleType<T> = T | T[];
interface TestType<T> {
a: ArrayOrSingleType<T>;
b: (v: ArrayOrSingleType<T>) => void;
}
const testVariable: TestType<number> = {
a: 4,
b: (v) => console.log(v)
}
testVariable.b([2]);
Now, I aim to maintain consistency so that testVariable.b([2])
triggers an error due to the fact that a
is a singular number
, not an array of number
s
After seeking help from ChatGPT, I received a solution:
type ArrayOrSingleType<T> = T extends any[] ? T[] : T;
interface NewTestType<T, U extends ArrayOrSingleType<T>> {
a: U;
b: (v: U) => void;
}
// This will generate an error
const example1: NewTestType<number, number> = {
a: 4,
b: (v: number[]) => console.log(v) // Error: 'v' should be a single number, not an array of numbers
}
// This one is correct
const example2: NewTestType<number, number[]> = {
a: [4],
b: (v: number[]) => console.log(v) // 'v' should be an array of numbers
}
However, I desire a solution where I can avoid specifying the type twice (e.g.,
const example2: NewTestType<number, number[]> = {
. I want to be able to declare const example2: NewTestType<number> = {