huan / ducks

Reducer Bundles Manager for Redux, Implemented the Ducks Modular Proposal
https://paka.dev/npm/ducks
Apache License 2.0
0 stars 0 forks source link

Protect String Literal Types in Action Types #1

Open huan opened 4 years ago

huan commented 4 years ago

When we define the redux action types in ducks, we will store them in a types.ts file:

const TEST = 'module/TEST'

Use export const TEST

And use import * as types from './types' in other TS module to import all the types.

In this way, the TEST can keep the string literal type as module/TEST, which is necessary for future usage.

Do NOT use export default { TEST }

In this way, the typeof TEST will become string, which will lose its string literal type.

If it lists its string literal type, then it seems more likely will cause the problem in future usage.

References

Using string constants as action type property:

please make sure to use simple string literal assignment with const. This limitation is coming from the type-system, because all the dynamic string operations (e.g. string concatenation, template strings and also object used as a map) will widen the literal type to its super-type, string. As a result this will break contextual typing for action object in reducer cases.

huan commented 4 years ago

There's another case related to this issue, is that the codebase can be passed the TSC but not be able to run by ts-node: https://github.com/TypeStrong/ts-node/issues/391#issuecomment-315470585

The reason is that ts-node will not load types.d.ts by default, we have to specify it explicitly in our ts file:

/// <reference path="./types.d.ts" />
huan commented 4 years ago

We can use const o = {} as const to keep the literal types.

See: https://stackoverflow.com/a/53662389/1123955