可以在枚举中返回一个接口。

huangapple go评论117阅读模式
英文:

Can I return an Interface within an Enum

问题

以下是翻译好的部分:

  1. 我得到以下错误:
  2. - 类型 '{ serial: string; }' 不能赋值给类型 'DataType'(2322)
  3. - 无法赋值给 'DataValidated',因为它是一个只读属性。(2540)
英文:

Can I return an Interface within an Enum?

  1. const PREFIX: string = 'TEST';
  2. interface DataValidated {
  3. serial: string;
  4. }
  5. enum DataType {
  6. Invalid,
  7. DataValidated
  8. }
  9. class DataValidate {
  10. validate(data: string) : DataType {
  11. if (data.startsWith(PREFIX)) {
  12. return DataType.Invalid;
  13. }
  14. return DataType.DataValidated = {
  15. serial: data,
  16. };
  17. }
  18. }

I am getting the following errors:

  • Type '{ serial: string; }' is not assignable to type 'DataType'.(2322)
  • Cannot assign to 'DataValidated' because it is a read-only property.(2540)

答案1

得分: 2

枚举在TS中无法包装值。请将返回类型更改为具有区分联合类型:

  1. interface DataInvalid {
  2. type: DataType.Invalid;
  3. }
  4. interface DataValidated {
  5. serial: string;
  6. type: DataType.DataValidated;
  7. }
  8. interface Data extends DataValidated | DataInvalid {}
  9. class DataValidate {
  10. validate(data: string): Data {
  11. if (data.startsWith(PREFIX)) {
  12. return { type: DataType.Invalid };
  13. }
  14. return {
  15. type: DataType.DataValidated,
  16. serial: data,
  17. };
  18. }
  19. }

这样编译器将能够推断出是否有数据,当您在data.type进行测试时。

英文:

Enums cannot wrap values in TS. Make your return type a discrimated union :

  1. interface DataInvalid {
  2. type: DataType.Invalid;
  3. }
  4. interface DataValidated {
  5. serial: string;
  6. type: DataType.DataValidated;
  7. }
  8. interface Data : DataValidated|DataInvalid
  9. class DataValidate {
  10. validate(data: string) : Data {
  11. if (data.startsWith(PREFIX)) {
  12. return {type: DataType.Invalid};
  13. }
  14. return = {
  15. type: DataType.DataValidated
  16. serial: data,
  17. };
  18. }
  19. }

That way the compiler will able to infer if there is data, when you're testing for data.type

huangapple
  • 本文由 发表于 2023年7月6日 17:01:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76627156.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定