Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Protect String Literal Types in Action Types #1

Open
huan opened this issue May 3, 2020 · 2 comments
Open

Protect String Literal Types in Action Types #1

huan opened this issue May 3, 2020 · 2 comments
Labels
documentation Improvements or additions to documentation

Comments

@huan
Copy link
Owner

huan commented May 3, 2020

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 added a commit to wechaty/ha that referenced this issue May 3, 2020
huan added a commit to wechaty/ha that referenced this issue May 4, 2020
@huan
Copy link
Owner Author

huan commented May 4, 2020

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: TypeStrong/ts-node#391 (comment)

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 added a commit to wechaty/ha that referenced this issue May 4, 2020
@huan
Copy link
Owner Author

huan commented May 20, 2020

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

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

@huan huan added the documentation Improvements or additions to documentation label May 22, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Improvements or additions to documentation
Projects
None yet
Development

No branches or pull requests

1 participant