2

我有一个实例,其中两个属性都必须是“数字”,并且我在事故中使用了一个而不是另一个。没有任何抱怨,调试这些需要一段时间。

我想知道是否可以扩展基本类型以确保当我尝试将 Age 类型的值分配给 Score 类型的变量时(两者都是数字)?

编辑:很抱歉最初的问题没有代码示例。Nurbol Alpysbayev 正确解释了我的问题,他的代码示例确实代表了我希望看到的情况:

type Score = number;
type Age = number;

let score: Score = 999;
let age: Age = 45;

score = age; // I want to have this line to throw an error
4

1 回答 1

3

问题的质量可能会好得多,但我想我理解了。

我相信你做了这样的事情:

type Score = number
type Age = number

let score: Score = 999
let age: Age = 45

score = age // no errors (and it confused you)

现在您的问题的答案是:两者Age和都是相同类型Score的类型别名,即. 这些名称只是为了方便起见,这就是为什么它们首先被称为别名number

因此,您将类型别名用于错误的任务。如果你需要区分类型,那么你必须使用这样的接口:

interface Score {type: 'score', value: number}
interface Age {type: 'age', value: number}

let score: Score = {type: 'score', value: 999}
let age: Age = {type: 'age', value: 45}

score = age // error

但是,您应该知道,对于表示分数和年龄的数据,您应该只保留类型number,而不要过度设计它们。

于 2019-02-17T15:41:08.083 回答