【问题标题】:Is it possible to type check String Aliases in TypeScript?是否可以在 TypeScript 中输入检查字符串别名?
【发布时间】:2018-07-29 15:48:58
【问题描述】:

鉴于此代码:

type Firstname = string
type Surname  = string

const firstname: Firstname = "John";
const surname:Surname = "Smith"

function print(name: Firstname) {
    console.log(name)
}

/*
 * This should give a compile error
 */

print(surname);

当函数需要Firstname 时,是否可以禁止传入Surname

【问题讨论】:

标签: typescript


【解决方案1】:

您正在寻找所谓的品牌类型。在 typescript 中,类型兼容性是由结构决定的,因此别名不会使类型不兼容,但我们可以使用交集类型和唯一符号使它们在结构上有所不同:

type Firstname = string & { readonly brand?: unique symbol }
type Surname = string & { readonly brand?: unique symbol }

const firstname: Firstname = "John"; // we can assign a string because brans is optional 
const surname: Surname = "Smith"

function print(name: Firstname) {
    console.log(name)
}

print(surname); // error unques symbol declarations are incompatible 

对此的不同变体可能有用,但基本思想是相同的,您可能会发现这些相似的答案很有用:guid definitionindex and position others

【讨论】:

  • @corgrath 添加了一些链接,希望对您有所帮助:-)
  • 最好在您的回答中包含与“名义类型”和“结构类型”问题相关的有用术语。
猜你喜欢
  • 1970-01-01
  • 2013-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-03
  • 1970-01-01
相关资源
最近更新 更多