繁体   English   中英

我应该在TypeScript中使用字符串文字作为返回值的类型吗?

[英]Should I use a string literal as a type of a returned value in TypeScript?

我有这样的实用方法:

private static getClassName(): 'my-component-class-name' {
    return 'my-component-class-name'
}

我使用精确的返回值作为返回类型,并且TypeScript正确编译了它,没有错误。

使用这种方法是一种好习惯还是应该在其中放置string

为了确保它不仅被忽略,我尝试了一下,打字稿显示了一个错误:

private static getClassName(): 'my-component-class-name' {
    return 'wrong-value'
}

这是错误:

类型“错误值”不能分配给类型“ my-component-class-name”。

这是使用此代码到TypeScript游乐场的链接

不推荐!

TypeScript是一个类型清除脚本,您应该使用显式类型作为返回类型。

TypeScript编译器将从字符串文字'my-component-class-name'getClassName()创建一个返回类型,它是Type Aliases ,等于type returnType = 'my-component-class-name' ,并将returnType设置为getClassName()的返回类型。 但是, return 'wrong-value' typeof 'wrong-value'是类型为typeof 'wrong-value'的类型,它是string类型,不等于已定义的returnType

如果您想让代码构建成功,只需添加| string 'my-component-class-name'之后'my-component-class-name' | string 这是一个联合类型。

代码段:

type returnType = "my-component-class-name";
var value: returnType = "my-component-class-name";

type returnType1 = "my-component-class-name" | string;
var value1: returnType1 = "union type";

type returnType2 = true;
var value2 : returnType2 = true;

type returnType3 = 1;
var value3: returnType3 = 1;

class A {
  public static getClassName(): returnType {
    return value;
  }

  public static getClassName1(): returnType1 {
    return value1;
  }

  public static getClassName2(): returnType2 {
    return value2;
  }

  public static getClassName3(): returnType3 {
    return value3;
  }
}

console.log(A.getClassName());
console.log(A.getClassName1());
console.log(A.getClassName2());
console.log(A.getClassName3());

输出为:

my-component-class-name
union type
true
1

键入别名文档: http : //www.typescriptlang.org/docs/handbook/advanced-types.html

如另一个答案中所述,编译器将忽略您的返回类型。 未来的编译器可能不会那么宽容。 如果您真的想声明一个常量,为什么不使用常量而不是函数呢? 或者,由于需要类名, 因此可以从JavaScript运行时获取它。

编辑添加:正如对该答案的评论所指出的那样, myObj.constructor.name可能无法经受缩小或其他类处理。 我之前在TypeScript中做过诸如getClassName函数之类的事情,但是当我更加认真地思考为什么要使用该名称时,最终会对其进行重构。 您可能会想出一些在JavaScript中未明确定义的特征,并且这些特征在将类转换为接口或mixin的重构中无法生存。 因此,可以考虑调用getXXXType方法,其中XXX描述了您最感兴趣的质量,例如getNumericalOperatorTypegetDateFormattingTypegetHipaCertificationType等。这也为您提供了喘息的机会,可以在发现自己的班级已经开始时添加各种类型的类型。 不止一个责任

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM