bcherny / json-schema-to-typescript

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

Export type vs. interface #307

Open eMarek opened 4 years ago

eMarek commented 4 years ago

I am testing json-schema-to-typescript and I see that in some cases it produces interface and in other cases type. What is the rule here, when does it make which? Is there an option if I would like to use only type?

bcherny commented 4 years ago

Hey, these are generally a little different. Interfaces with the same name will be merged by TSC, which is important for emitting duplicates (otherwise, we’d need to prune these ourselves and build our own type DAG, which can be expensive).

Extensions also work a little different for type vs. interface, and it would be undesirable to have to support semantics for both.

Is there a reason you’re interested in sticking to one vs. both for your use case?

See https://github.com/bcherny/json-schema-to-typescript/blob/master/src/generator.ts for when we emit one vs. the other.

eMarek commented 4 years ago

Interfaces with the same name will be merged by TSC

This is exact reason why I prefer types. I don't want TypeScript to do some under the hood magic which can result into bugs. Imagine that there is an interface somewhere in the code which I am not aware of it and then the same interface will be generated out of JSON schema. Two totally unrelated things will be represented as one.

So there are no plans in the future to pick between interface and type?

scaleflake commented 3 years ago

I agree that there should be an option to choose between interface and type. In my case, the interface don't fit due to this issue: https://github.com/microsoft/TypeScript/issues/15300

swain commented 3 years ago

+1 -- this definitely needs to be configurable somehow. More recent versions of TypeScript have introduced more significant different handling between types + interfaces, so there is definitely semantic difference.

Perhaps a custom JSONSchema attribute could override the default? e.g.

{
  "type": "object",
  "title": "MyType",
  "tsUseType": true
}

I'd be happy to PR this change, if you'd be open to reviewing @bcherny.

johann1301s commented 3 weeks ago

I suggest dropping interface completely: https://www.youtube.com/watch?v=oiFo2z8ILNo.