Skip to content

Replace const enum in .d.ts with string literal union #15

Closed
@mz8i

Description

@mz8i

Thanks for the great library!
I'm having an issue related to #6 after using the suggested fix to #14

The problem is that importing const enum from a .d.ts file doesn't really work properly.

Consider the following fix to #14:

  csvSchema.cols.forEach((c) => {
    c.type = 's';
  });

This results in a TS error:
image

You can silence the error by forcing a cast to SchemaColumnType like this:

  csvSchema.cols.forEach((c) => {
    c.type = 's' as SchemaColumnType;
  });

but this is not recommended because it essentially removes the type checking, and if SchemaColumnType changes, or someone passes a wrong type value, TypeScript will not pick up the error:

image

I would suggest removing the const enum from the .d.ts and replacing it with a string literal union, which I think is the correct way to provide good DX here. Like this (I'll submit this exact suggestion as a PR):

export type SchemaColumnType = 
| /** String */ 's'
| /** Number */ 'n'
| /** Date */ 'd'
| /** JSON */ 'j'
| /** Boolean_1 */ 'b:1'
| /** Boolean_t */ 'b:t'
| /** Boolean_T */ 'b:T'
| /** Boolean_true */ 'b:true'
| /** Boolean_True */ 'b:True'
| /** Boolean_TRUE */ 'b:TRUE'
| /** Boolean_y */ 'b:y'
| /** Boolean_Y */ 'b:Y'
| /** Boolean_yes */ 'b:yes'
| /** Boolean_Yes */ 'b:Yes'
| /** Boolean_YES */ 'b:YES';

This will also give autocomplete:
image

Now, the only bit where this is not perfect is that the single-character strings are a bit less obvious than the names of the const enum elements. And currently, TypeScript sadly does not pick up the comments next to the union elements. But once it does (microsoft/TypeScript#38106), the comments should be included in IntelliSense.
But anyway, considering that the const enum approach is either incorrect or dangerous (depending on how you look at it), I think this is still a better alternative.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions