devexperts / swagger-codegen-ts

Typesafe Swagger API generator for TypeScript
Mozilla Public License 2.0
80 stars 16 forks source link

prohibit extra fields in request payload #182

Open Geksanit opened 8 months ago

Geksanit commented 8 months ago

problem: If I send the payload with extra fields, then I get an error in the rest. rest does not expect extra fields.

interface ProductModify {
  name: string;
}
interface Product extends ProductModify {
  id: string;
  foo: number;
}
const product: Product = { name: 'TEST', id: '1', foo: 1 };
const modifyProduct = (product: ProductModify) => {};
modifyProduct(product); // no type errors, because Product compatible with ProductModify

I propose to prohibit extra fields, i.e. disable polymorphism.

type Impossible<K extends keyof any> = {
  [P in K]: never;
};
export type NoExtraProperties<T, U extends T = T> = U & Impossible<Exclude<keyof U, keyof T>>;

const modifyProduct = <T extends ProductModify>(product: NoExtraProperties<ProductModify, T>) => {};
modifyProduct(product); // type error: Argument of type 'Product' is not assignable to parameter of type 'NoExtraProperties<ProductModify, Product>'
kokovtsev commented 8 months ago

This can be easily done by wrapping each generated type into io-ts' exact.

On the other hand, it is desirable sometimes to pass extra fields to the server, for example for features like "custom data" where the system objects can be extended with customer-specific fields.

Looks like this should be controlled by the additionalProperties parameter in schemas, WDYT? https://www.apimatic.io/openapi/additionalproperties