I'm just starting discovering TypeScript and I'm testing the limits. What I'm looking for is a way to make an interface that as fields depending on the value of one of it's property.
For example:
type type RecursiveArray<T> = T | RecursiveArray<T>[];
type allowedTypesString = 'string' | 'email' | 'date' | 'id' | 'number' | 'boolean' | 'object';
interface IOptions {
type: RecursiveArray<allowedTypesString>,
required?: boolean,
defaultValue?: PROVIDED_TYPE,
expected?: PROVIDED_TYPE[],
transform?: (value: PROVIDED_TYPE) => any,
validate?: (value: PROVIDED_TYPE) => boolean,
regexp?: RegExp,
min?: number,
max?: number,
params?: object,
}
I want IOptions to have:
regex
property only iftype
is "string" or "email" .params
only iftype
is "object".min
andmax
only iftype
is "number, etc...
I saw that I could use discriminated unions like in this thread, but as you can see, the type
property is a RecursiveArray<allowedTypesString>
which means that it can be a single string, an array of string, an array of array of string, etc...
With unions, I could declare :
interface IOptionsString {
type: string,
defaultValue?: string,
expected?: string[],
regexp?: RegExp,
}
that will be called if the type
is a string. But what if I'm receiving an array of string or an array of array of string ?
Is what I'm doing possible ? Otherwise I'll just handle single array but I want to know if what I'm thinking of is possible in TypeScript.
Thanks for your help !