#Type a variable based on another variable

1 messages · Page 1 of 1 (latest)

bright basalt
#

I have two variables, type and value.

type IInputType = 'text' | 'number' | 'boolean' | 'object' | 'percent' | 'time' | 'date' | 'autocomplete'

export let inputType : IInputType = 'text';

export let value: number | string | boolean = '';

I need to specify that, when inputType is text, value can only be string or number. If inputType is boolean, then value can only be of type boolean. How can I do that?

graceful willow
#

something like this?

weary bloomBOT
#
that_guy977#0

Preview:```ts
type IInputType = 'text' | 'number' | 'boolean' | 'object' | 'percent' | 'time' | 'date' | 'autocomplete'

export const inputType = 'text' satisfies IInputType;

interface InputTypeMap {
text: string;
number: number;
boolean: boolean;
object: unknown;
percent: unknown;
...```

graceful willow
#

ah wait misunderstood the condition

#

well once you have a literal type for inputType you can use any conditionals or indexing with it

tawdry sapphire
#

the specific export arrangement kinda confuses me, but maybe more like this:

weary bloomBOT
#
mkantor#0

Preview:```ts
...
type CorrelatedInputTypeAndValue = {
[I in InputType]: {
inputType: I
value: InputTypeMap[I]
}
}[InputType]

export const {
inputType,
value,
} = {
inputType: 'text',
value: 'hello world',
} satisfies CorrelatedInputTypeAndValue```

tawdry sapphire
#

simplified: