Closed spexii closed 1 year ago
Hi, additionalProperties: false,
may help.
const UserSchema = {
type: 'object',
properties: {
id: { type: 'string' },
name: { type: 'string' },
},
additionalProperties: false,
required: ['id', 'name'],
} as const
type User = FromSchema<typeof UserSchema>
type NewUser = Omit<User, 'name'>
Hi @spexii!
This is not intended but is not due to FromSchema
but rather the way TS implements Omit
as Pick<T, Exclude<keyof T, K>>;
Because you allowed additionalProperties
(notice the [x:string]: unknown
in User
), keyof T
is typed as string | number
and so is the exclusion. Pick<User, string | number>
will return the unexpected result.
My suggestions:
additionalProperties: false
if it's compliant with your code basetype NewUser = Pick<User, 'id'>
insteadIf none of those match your needs, you can always fallback on your properties
keyword keys:
type NewUser = Pick<User, Exclude<keyof typeof UserSchema.properties, "name">>
Hope this solves your issue!
Thank you both! And thanks @ThomasAribart for the thorough explanation and different ways to solve this issue. :)
If I'm just creating a type from schema with the following simple example, everything goes as expected; the type
User
hasid
andname
.However, if I create a new type of that type
User
usingOmit
, also theid
property gets lost. And if I create a new object and type it withNewUser
, TS is happy with the empty object.I also tried to extend the type
User
, and it did the same regarding the original properties. The extended properties are in place.Am I missing something and/or is this intended?