简体   繁体   English

打字稿:与基本类型平行的自定义类型被忽略

[英]Typescript: Custom type that parallels base type ignored

Expectation: If I create a custom type that parallels an existing type I expect to see variables assigned that type maintain that type and not fallback to to the paralleled base type.期望:如果我创建一个与现有类型并行的自定义类型,我希望看到分配给该类型的变量保持该类型,而不是回退到并行基类型。 The function f below should return a Dog type instead a string type.下面的函数f应该返回Dog类型而不是string类型。

type Dog = string;

const f = (dog: Dog): Dog => {
    return dog;
};

Reality:现实: 狗

Is there a reason why Typescript does this? Typescript 这样做有什么原因吗? Is this a bug?这是一个错误吗? I realize both approaches are by definition equivalent but I would like to use my custom types for readability.我意识到这两种方法在定义上是等效的,但我想使用我的自定义类型来提高可读性。 Any thoughts?有什么想法吗?

I think this will help you learn more about aliases.我认为这将帮助您了解有关别名的更多信息。

Aliasing doesn't actually create a new type - it creates a new name to refer to that type. 别名实际上并不创建新类型 - 它创建一个新名称来引用该类型。

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

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