bcherny / json-schema-to-typescript

Compile JSON Schema to TypeScript type declarations
https://bcherny.github.io/json-schema-to-typescript-browser/
MIT License
2.92k stars 392 forks source link

Is there a way to define how types are written? #599

Closed chris-acuvity closed 3 months ago

chris-acuvity commented 3 months ago

Currently json-schema-to-typescript generates the following code:

export type Operator =
  | "Equals"
  | "NotEquals"
  | "Contains"
  | "NotContains"
  | "EqualsOrGreaterThan"
  | "EqualsOrLesserThan"
  | "OneOf"
  | "Empty"
  | "NotEmpty"; 

// same for keys
// same for values

export interface Predicate {
  key: Key;
  operator: Operator;
  values: Values;
}

It is valid and working fine, however, I could not find a way to enumerate all the possible values of an operator for other operation. For instance, I would want to create a Record<Operator, string> to translate the Operator.

I want to avoid writing the following to make sure when my schema changes, the dictionnary changes too:

const translation = {
 "Equals": "is equal to",
 "NotEquals": "does not equal",
  // and everything else is also done manually...
}

The problem above is that I need to re-instanciate a new string for each operator.

Is there a way to do this in TypeScript or a way to change the json-schema-to-typescript output ?

I have been looking at this article which suggest to have something like:

export const OperatorValues = ['Equals', 'NotEquals'] as const; 
type OperatorType = typeof OperatorValues[number]; 

Thanks for your input 🙏

bcherny commented 3 months ago

You want to add an explicit type annotation to translation, to tell TypeScript that you expect it to have all the keys.

const translation: Record<Operator, string> = {
...

https://www.typescriptlang.org/play/?ssl=12&ssc=48&pln=12&pc=1#code/KYDwDg9gTgLgBDAnmYcDyKoEMbTgXgCg44AfOAIgFEBHAVywBsBnC4sygOQhloZbYlyFAMIQAdjCwBLca3bDuMMZJlzBHavSbM0UAOJRgOYFAAqACyziNwvjr0AZYM2anL125TTjgaAGZe1AC2YEhBSlSh4QDccISEAMYSzPAw2HKMONISAFxwAErAyVAAJgA8GKY40AA0cKlQsgDmAHwEcADexFr8rPkU0sxwwNqMCBAUtT2RY-2UpRAucOI8I2NT7AD0W3DWpSMAbqaIMBYtIyyoQ3ssEHCLvnDB1vyMiAB0X4QAvkA