gpt4 book ai didi

reactjs - 什么是 Typescript 中的常量/类型模式

转载 作者:搜寻专家 更新时间:2023-10-30 21:39:37 24 4
gpt4 key购买 nike

export const INCREMENT_ENTHUSIASM = 'INCREMENT_ENTHUSIASM';
export type INCREMENT_ENTHUSIASM = typeof INCREMENT_ENTHUSIASM;


export const DECREMENT_ENTHUSIASM = 'DECREMENT_ENTHUSIASM';
export type DECREMENT_ENTHUSIASM = typeof DECREMENT_ENTHUSIASM;

这里发生了什么?我无法理解这一点。这很令人困惑这是从这里https://github.com/Microsoft/TypeScript-React-Starter添加操作部分下。

我知道 type 关键字的作用,但在这里看起来很困惑。

enter image description here

最佳答案

您发布的示例背后的想法是导出一个值和一个类型,这样您就可以执行如下操作:

let myVar: INCREMENT_ENTHUSIASM;

如果行:

type INCREMENT_ENTHUSIASM = typeof INCREMENT_ENTHUSIASM

缺少上述变量声明会引发错误:

Cannot find name 'DECREMENT_ENTHUSIASM'

typescript 中的某些东西既是类型又是值,例如枚举和类,但接口(interface)或类型别名只是类型,在这种情况下,您还可以重用类型名称来创建值。
例如:

type MySingleton = {
getId(): string;
doSomething1(str: string): string;
doSomething2(num: number): number;
}

const MySingleton: MySingleton = {
getId: function () {
...
},
doSomething1: function(str: string): string {
...
},
doSomething2: function (num: number): number {
...
}
}

更多关于 typescript 中的类型/值的信息:Declaration Merging - Basic Concepts


编辑

type INCREMENT_ENTHUSIASM = typeof INCREMENT_ENTHUSIASM;

等于:

type INCREMENT_ENTHUSIASM = "INCREMENT_ENTHUSIASM";

这使得 INCREMENT_ENTHUSIASM 成为一个只能是 "INCREMENT_ENTHUSIASM" 的字符串。

关于reactjs - 什么是 Typescript 中的常量/类型模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44884838/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com