#Typescript not narrowing after throw/never

9 messages · Page 1 of 1 (latest)

native frostBOT
#
andy.ray#0

Preview:```ts
// Setup
type a = 'a';
type b = 'b';

const isA = (x:any):x is a => x === 'a';

const fail = (msg: any): never => {
throw new Error(msg);
};

// Code
const someFn = ():a | b => {
if(Math.random()> 0.5) {
return 'a';
}
return 'b';
};
const y = someFn();
...```

tacit hearth
#

@azure aspen Hmm, this is a bit odd, but it works with a function declaration

#
function fail(msg: any): never {
  throw new Error(msg);
};
azure aspen
#

wtf

half yarrow
#

It also works if you annotate the type of fail, rather than the type of the function:

const fail: (msg: any) => never = (msg) => {
  throw new Error(msg);
};
#

The "hover type" implies that it's the same type, but apparently isn't... same behavior back to TS 3.7.5

#

A similar-ish formulation gives... interesting... results.

native frostBOT
#
gerrit0#0

Preview:```ts
const ok_1 = (msg: unknown): asserts msg => {}
// ^?

const ok_2: (msg: unknown) => asserts msg = msg => {}
// ^?

function test1(): "b" {
const value = Math.random() ? "a" : "b"
// ^?

ok_1(value !== "a")
return value
}

function test2(): "b"
...```