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

时间:2018-07-29 06:50:26

标签: typescript

给出以下代码:

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

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

1 个答案:

答案 0 :(得分:4)

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

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