3

The web audio API has its own types, one of them is BiquadFilterType

type BiquadFilterType = "lowpass" | "highpass" | "bandpass" | "lowshelf" | "highshelf" | "peaking" | "notch" | "allpass"

I'm using a to let the user select which of the types he or she is going to use. So I made a function which receives a string (from the selector) and sets the biquadfilter.type to the received value so I had to give it a signature like

setValue(value: BiquadFilterType) ...

But when I try to call my function where the selector is ts complains that I'm giving the function a string whilst it was expecting a BiquadFilterType. Is there any way of checking (inside my function) the type (I've tried typeof and instanceof but none seem to make sense for TS) of the received argument so that TS knows that I'm using it correctly?

Gabriel Yshay
  • 63
  • 2
  • 5

1 Answers1

2

Typescript compiles to Javascript, and all types are removed when this happens. So the only way to validate input is manually at runtime by type guard.

function isBiquadFilter(value: string = ""): value is BiquadFilterType {
  switch(value) {
     case "lowpass":
     case "highpass":
     ...
     case "allpass":
        return true;
     default:
        return false;
  }
}

Then, if you put it in an if-statement, Typescript will be happy:

const filter: string = getBiquadFilterFromUntrustedSource();
if (isBiquadFilter(filter)) {
   // filter is now casted as type BiquadFilterType
   setValue(filter);
} else {
   // filter is now casted as string. Handle appropriately.
}

Or if you want it in the setValue part:

function setValue(filter) {
   if (isBiquadFilter(filter)) {
      // Perform Action
   } else {
      // throw error
   }
}
DeeV
  • 35,865
  • 9
  • 108
  • 95