-
-
Notifications
You must be signed in to change notification settings - Fork 5
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Refine isReadonlyOf
and related
#60
Comments
Several pattern to annotate fields as import { is, Predicate } from "./mod.ts";
function optional<K extends PropertyKey>(name: K): K {
return name;
}
function readonly<K extends PropertyKey>(name: K): K {
return name;
}
function annotate<T>(
pred: Predicate<T>,
annotations: { optional?: boolean; readonly?: boolean },
): Predicate<T> {
return pred;
}
const as = {
Optional: <T>(pred: Predicate<T>) => pred,
Readonly: <T>(pred: Predicate<T>) => pred,
};
const pattern1 = is.ObjectOf({
[optional("optionalField")]: is.String,
[readonly("readonlyField")]: is.String,
[readonly(optional("readonlyOptionalField"))]: is.String,
});
const pattern2 = is.ObjectOf({
optionalField: annotate(is.String, { optional: true }),
readonlyField: annotate(is.String, { readonly: true }),
readonlyOptionalField: annotate(is.String, {
optional: true,
readonly: true,
}),
});
const pattern3 = is.ObjectOf({
optionalField: as.Optional(is.String),
readonlyField: as.Readonly(is.String),
readonlyOptionalField: as.Readonly(as.Optional(is.String)),
}); I personally like |
The optional annotation is also used as an element of |
What I'm thinking of it is
type A = {
foo?: string;
readonly bar: string;
readonly hoge?: string;
};
// Predicate<A>
const a = is.ObjectOf({
foo: as.Optional(is.String),
bar: as.Readonly(is.String),
hoge: as.Optional(as.Readonly(is.String)),
});
type B = Partial<A>;
// Predicate<B>
const b = is.PartialOf(a);
type C = Readonly<A>;
// Predicate<C>
const c = is.ReadonlyOf(a); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
TypeScript offers the
Readonly<T>
type function and thereadonly
keyword. However, theisReadonlyOf
function seems a bit ambiguous. I propose the following improvements:isReadonlyOf
for Array, Tuple, and Object types.isReadonlyFieldOf
for checking/annotating thereadonly
status of object fields.isOptionalOf
toisOptionalFieldOf
to maintain consistency withisReadonlyFieldOf
. This change aligns with the handling of?
for object fields.The text was updated successfully, but these errors were encountered: