#Static analyser not working for variable of `typeof`

1 messages · Page 1 of 1 (latest)

clever sundial
#

Is there a way to convince the static analyser to narrow types based on a variable of the typeof operator.

type Arg = number | boolean | string | Date

function doString(s: string) { return s }
function doBoolean(b: boolean) { return b }

function doStuff(a: Arg) {
  const t = typeof a
  if (t === 'boolean') return doBoolean(a).toString()
  else if (t === 'string') return doString((a as string)) // This seems futile...
  else if (typeof a === 'string') return doString(a) // This is ok
  else return a.toString()
}

I know that in this case you can just use a switch statement, but what if my checking is a bit more complicated ans also has a Array.isArray.

errant nexus
#

storing the result of the typeof test in a separate variable decouples it from its source

#

instead, repeat typeof a to preserve the narrowing

#

if you are testing t === "string", for the compiler, you are only narrowing t, not a

#

so a stays as Arg

#

@clever sundial

fleet lintelBOT
#
ascor8522#0

Preview:```ts
type Arg = number | boolean | string | Date

declare function doString(s: string): string
declare function doBoolean(b: boolean): boolean

function doStuff(a: Arg) {
if (typeof a === "boolean")
return doBoolean(a).toString()
if (typeof a === "string") return doString(a) // This is
...```

errant nexus
#

!ts

fleet lintelBOT
#
type Arg =
    | number
    | boolean
    | string
    | Date;

declare function doString(s: string): string;
declare function doBoolean(b: boolean): boolean;

function doStuff(a: Arg) {
    if (typeof a === 'boolean') return doBoolean(a).toString();
    if (typeof a === 'string') return doString(a); // This is ok
    return a.toString()
}
sour charm