Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can two different TypeScript interfaces be required to have the same keys but be able to have different values?

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
  }
}
like image 494
Joey Farina Avatar asked Oct 18 '22 19:10

Joey Farina


1 Answers

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
  }
}
like image 155
Amid Avatar answered Oct 21 '22 09:10

Amid