Skip to content

Protect String Literal Types in Action Types #1

@huan

Description

@huan

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationImprovements or additions to documentation

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions