TypeScript 带有默认值和类型推断的区分联合类型

7

我希望创建一个带有判别值的联合类型,但不需要传递判别值。

以下是我的当前代码:

interface Single<T> {
  multiple?: false // this is optional, because it should be the default
  value: T
  onValueChange: (value: T) => void
}

interface Multi<T> {
  multiple: true
  value: T[]
  onValueChange: (value: T[]) => void
}

type Union<T> = Single<T> | Multi<T>

我使用以下内容进行测试:

function typeIt<T>(data: Union<T>): Union<T> {
    return data;
}

const a = typeIt({ // should be Single<string>
    value: "foo",
    onValueChange: (value) => undefined // why value is of type any?
})

const b = typeIt({ // should be Single<string>
    multiple: false,
    value: "foo",
    onValueChange: (value) => undefined
})

const c = typeIt({ // should be Multi<string>
    multiple: true,
    value: ["foo"],
    onValueChange: (value) => undefined
})

但是我收到了一堆错误和警告...

  1. const aonValueChange 中,参数 value 的类型是 any。当显式设置 multiple: false(例如在 const b 中)时,它会被正确地推断为 string

  2. const c 根本不起作用。我得到了这个错误:"Type 'string' is not assignable to type 'string[]'"

您有任何解决方法吗?

我用这段代码创建了一个TypeScript Playground


如果您正在使用泛型类型,则应指定类型,这也有助于其他开发人员。 - Pavlo
1
@Pavlo,我非常不同意。TS的强大之处在于它能够推断类型(我已经推断出了一些非常复杂的类型)。此外,明确指定类型基本上是重复信息,如果类型没有明确命名,这可能会特别痛苦。 - Titian Cernicova-Dragomir
1
值得注意的是,1已在此处记录(https://github.com/microsoft/TypeScript/issues/41759),2已在3.6版本中修复。 - Erik
1个回答

5

我认为编译器很难在检查回调函数时推断出value参数的类型,因为在确定对象文字的类型之前,回调函数的类型仍未确定。

如果您没有很多联合成员,则可以使用多个重载来实现预期的解决方案:

export interface Single<T> {
  multiple?: false // this is optional, because it should be the default
  value: T
  onValueChange: (value: T) => void
}

interface Multi<T> {
  multiple: true
  value: T[]
  onValueChange: (value: T[]) => void
}

type Union<T> = Single<T> | Multi<T>

function typeIt<T>(data: Single<T>): Single<T>
function typeIt<T>(data: Multi<T>): Multi<T>
function typeIt<T>(data: Union<T>): Union<T> {
    return data;
}

const a = typeIt({ // is Single<string>
    value: "foo",
    onValueChange: (value) => undefined // value is typed as expected
})

const b = typeIt({ // is Single<string>
    multiple: false,
    value: "foo",
    onValueChange: (value) => undefined
})

const c = typeIt({ // is be Multi<string>
    multiple: true,
    value: ["foo"],
    onValueChange: (value) => undefined
})

谢谢。运作得非常好! - Benjamin M

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接