hebcal / hebcal-es6

perpetual Jewish Calendar with holidays, Shabbat and holiday candle lighting and havdalah times, Torah readings, and more
https://hebcal.github.io/api/core/
GNU General Public License v2.0
100 stars 14 forks source link

use of const enum may produce unexpected results #357

Closed bennypowers closed 10 months ago

bennypowers commented 10 months ago

Shavua tov.

The flags dict is defined as a typescript const enum. This can lead to difficulties:

https://www.typescriptlang.org/play?target=9&jsx=0#code/JYWwDg9gTgLgBAbzgMwDYEMDmBnOBfFKCEOAcgAEALAUwCMBjdVAenumtIG4AobtgO2zxkcALxwA8rQBW1ejAB0yIiACi-GFGDVsACimz5C6hq07d3OFbjNmccjGwBaagA8wcmC6hEoALjgAd0p0GGoAN2ooS2s0LGxuAEpEnj4IQQhUagVUCExdZBTeAWxM7Nz8uJwFAGEACQBBAHFEoA

Input:

import { flags } from '@hebcal/core';

const f = Object.fromEntries(Object.entries(
    // @ts-expect-error: whatever
    flags
));

console.log(f);

console.log(flags.CHAG)

Output:

const f = Object.fromEntries(Object.entries(
// @ts-expect-error: whatever
flags));
console.log(f);
console.log(0 /* flags.CHAG */);
export {};

The correct flag for CHAG is 1. Code relying on flags.CHAG and thus-compiled will fail. I worked around this by copying the flags table into my code. A better solution would be to export the table as an object

export const flags = {
  // ...
} as const;

An even better solution would be to vend predicates instead of bitmasks.

Besoros tovos

mjradwin commented 10 months ago

Thanks for the bug report! We're sorry about TypeScript errors. Can you try 4.5.1 and let us know if this fixes the problem for you?

bennypowers commented 10 months ago

https://github.com/hebcal/hebcal-es6/commit/dd5b87f00f249494067000faecfab36c6ed2b6ef seems to fix it

if you adopt ts sources, let me suggest using export const flags = {/*..*/} as const instead, which is more flexible