// 定义类型别名,这里以数字操作相关类型为例
type NumberOperand = number;
type NumberOperator = '+' | '-' | '*' | '/';
// 定义函数,接受两个参数,一个操作数和一个操作符
function calculate(operand: NumberOperand, operator: NumberOperator): number {
switch (operator) {
case '+':
return operand + operand;
case '-':
return operand - operand;
case '*':
return operand * operand;
case '/':
return operand / operand;
default:
return NaN;
}
}
类型别名遵循一致性原则说明
- 命名逻辑关联:在上述代码中,
NumberOperand
代表数字操作数,NumberOperator
代表数字操作符,从命名上可以清晰看出两者都与数字操作相关,都以 Number
作为前缀,表明它们属于同一领域的相关类型。
- 结构逻辑关联:
NumberOperand
是 number
类型,而 NumberOperator
是一组与数字运算操作符相关的字面量联合类型,它们在结构上都围绕数字运算这一主题展开,操作数和操作符在逻辑上是进行数字计算必不可少的元素,紧密相关。