D
D
Dadad2020-11-10 19:58:59
typescript
Dadad, 2020-11-10 19:58:59

How to determine the type of a variable depending on the type of another?

There is a code for ts:

interface ModelOptions {
  value: [number, number] | number
  range: boolean
}

How to set value to type [number, number] if range === true and vice versa?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Lynn "Coffee Man", 2020-11-10
@Dadad

As close as possible to the desired is Discriminating Unions

interface ModelOptionRange {
  value: [ number, number ];
  range: true;
}

interface ModelOptionValue {
  value: number;
  range: false;
}

type ModelOption = ModelOptionRange | ModelOptionValue;

function check(v: number, cond: ModelOption): boolean {
  if (cond.range) {
    // тут cond точно типа ModelOptionRange
    const [ min, max ] = cond.value;
    return (min <= v && v <= max);
  } else {
    // а тут ModelOptionValue
    return v === cond.value;
  }
}

sandbox

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question