I want to be able to enforce that objValidator has the same keys as the obj that it validates. Is this possible in TypeScript? Any ideas on how I can implement something like this below? Mainly the obj and objValidator must have the same keys, but the key values are different.
I would like to be able to be warned if my objValidator does not have the exact same keys as the obj.
interface obj {
alpha: number
beta: string
}
interface objValidator {
alpha: {
message: string
valid(ALPHA'S TYPE): boolean
}
beta: {
message: string
valid(BETA'S TYPE): boolean
}
}
Something like this using mapped types maybe:
interface Obj {
alpha: number
beta: string
}
type Validator<T> = {
[P in keyof T]: {message: string, valid: boolean};
};
let o: Obj = { alpha: 1, beta: "123" };
let v: Validator<Obj> =
{
alpha: {
message: "ok",
valid: true
},
beta: {
message: "not ok",
valid: false
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With