简体   繁体   English

"是否可以在 TypeScript 中输入检查字符串别名?"

[英]Is it possible to type check String Aliases in TypeScript?

Given this code:鉴于此代码:

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);

You are looking for what is called branded types.您正在寻找所谓的品牌类型。 In typescript type compatibility is decided structurally so the alias will not make types incompatible but we can make them structurally different using an intersection type and a unique symbol:在打字稿中,类型兼容性是在结构上决定的,因此别名不会使类型不兼容,但我们可以使用交集类型和唯一符号使它们在结构上有所不同:

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 

Different variations on this may be useful but the basic idea is the same, you might find these similar answers useful : guid definition , index and position , and others对此的不同变体可能有用,但基本思想是相同的,您可能会发现这些相似的答案很有用: guid definition , index and position

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

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