Допустим, у меня есть два типа: X
и Y
type X = 'foo';
type Y = 'bar';
И у меня есть следующий дискриминированный союз:
type DiscriminatedUnion =
| {
type: 'X',
fn: (arg: X) => void;
arg: X;
}
| {
type: 'Y',
fn: (arg: Y) => void;
arg: Y;
}
Итак, ясно, что этот объект типа DiscriminatedUnion
будет иметь как fn
, так и arg
одного типа: либо X
, либо Y
. Почему TS не может скомпилировать следующую функцию?
function acceptsUnion(union: DiscriminatedUnion): void {
// it's obvious, that both fn and arg would be either X, or Y, but strictly the same type
const {fn, arg} = union;
fn(arg); // TS Error: Argument of type 'string' is not assignable to parameter of type 'never'. Type 'string' is not assignable to type 'never'
}