【问题标题】:Typescript: Custom type that parallels base type ignored打字稿:与基本类型平行的自定义类型被忽略
【发布时间】:2020-07-11 07:55:34
【问题描述】:

期望: 如果我创建一个与现有类型平行的自定义类型,我希望看到分配给该类型的变量会保持该类型,而不是回退到并行的基本类型。下面的函数f 应该返回Dog 类型而不是string 类型。

type Dog = string;

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

现实:

Typescript 这样做有什么原因吗?这是一个错误吗?我意识到这两种方法在定义上是等效的,但我想使用我的自定义类型来提高可读性。有什么想法吗?

【问题讨论】:

    标签: javascript node.js typescript visual-studio-code types


    【解决方案1】:

    我认为这将帮助您了解有关别名的更多信息。

    Aliasing doesn’t actually create a new type - it creates a new name to refer to that type.

    【讨论】:

    • 谢谢 - 正是我所缺少的。
    猜你喜欢
    • 2021-01-29
    • 2020-09-27
    • 2020-08-29
    • 1970-01-01
    • 2020-03-18
    • 2021-08-20
    • 2020-05-07
    • 2019-07-12
    • 1970-01-01
    相关资源
    最近更新 更多