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;
what is happening here? I am not able to understand this.It is very confusing This is from here https://github.com/Microsoft/TypeScript-React-Starter under Adding actions section.
I know what type keyword do but it seems very confusing here.
Typescript constants are variables, whose values cannot be modified. We declare them using the keyword const . They are block-scoped just like the let keyword. Their value cannot be changed neither they can be redeclared. Const keyword is part of the es2015 (es6) specification of the javascript.
const is an augmentation of let in that it prevents re-assignment to a variable. With TypeScript being an extension of JavaScript, the language naturally supports let and const .
The ReturnType in TypeScript is a utility type which is quite similar to the Parameters Type. It let's you take the return output of a function, and construct a type based off it.
Use var and let to define any variable, with or without type or initial value. We use the const keyword initialize a constant whose value does not change. Hence we must initialize it with a value. You can not use it to declare a variable where there is no initial value.
The idea behind the example you posted is to export both a value and a type so that you'll be able to do something like:
let myVar: INCREMENT_ENTHUSIASM;
If the line:
type INCREMENT_ENTHUSIASM = typeof INCREMENT_ENTHUSIASM
was missing the above variable declaration would have raised an error:
Cannot find name 'DECREMENT_ENTHUSIASM'
Some things in typescript are both a type and a value, suchs as enums and classes, but an interface or a type alias are only types, and in such cases you can then reuse the type name to create a value as well.
For example:
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 {
...
}
}
More on types/values in typescript here: Declaration Merging - Basic Concepts
type INCREMENT_ENTHUSIASM = typeof INCREMENT_ENTHUSIASM;
Is equal to:
type INCREMENT_ENTHUSIASM = "INCREMENT_ENTHUSIASM";
Which makes INCREMENT_ENTHUSIASM
a string that can only be "INCREMENT_ENTHUSIASM"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With