是否可以使用静态变量进行类型定义?

bai*_*idz 1 typescript

我有一些带有指示其类型的静态变量的类。我想基于这些静态变量创建一个联合类型

class Foo {
  static typeId = 'i-am-foo';
}

class Bar {
  static typeId = 'i-am-bar';
}

type MyUnionType = Foo.typeId | Bar.typeId;
Run Code Online (Sandbox Code Playgroud)

TS游乐场

不幸的是这是不可能的,我收到错误

“Foo”仅指一种类型,但在这里用作命名空间。

是否可以使用静态变量进行类型定义?

Tus*_*ahi 5

i-am-fooi-am-bar是值,而不是类型,您正在尝试访问它们并组合起来创建一个联合。要正确执行此操作,您需要使用 来获取它们的类型typeof

另外,请使用正确的类型正确输入静态值。如果您不指定:

  static typeId :'i-am-foo'= 'i-am-foo';
Run Code Online (Sandbox Code Playgroud)

的类型typeId将是广泛类型string,并且两种string类型的并集将是string

注意:另一种方法是:

  static typeId = 'i-am-foo' as const;
Run Code Online (Sandbox Code Playgroud)

as const会告诉 TS 尝试找到最窄的类型。

你的代码看起来像:

class Foo {
  static typeId :'i-am-foo'= 'i-am-foo';
}

class Bar {
  static typeId : 'i-am-bar' = 'i-am-bar';
}

type MyUnionType = typeof Foo.typeId | typeof Bar.typeId;
Run Code Online (Sandbox Code Playgroud)

操场

  • @baitendbidz 如果你有很多具有相同判别属性的类,你也可以使用这种语法进行联合,以避免每次重复属性名称: [`(typeof Foo | typeof Bar)['typeId']` ](https://www.typescriptlang.org/play?noUncheckedIndexedAccess=true&target=99&jsx=4&useUnknownInCatchVariables=true&exactOptionalPropertyTypes=true#code/MYGwhgzhAEBiD29oG8BQ1oQC5iwS2GiwE8AHAUwEkATaAXmgHI8BaMAWxYDNFHpJoweADtsAblQBfVKl CQYAITAAnFOkw58hEhRr0mrDiwBGKvgKGisE6ah3loAWWIBVYXhEAVMg4YAKe3guOERoAB8iHyDoJWUASgBtRnsaRgBdCSA) (2认同)