Home > OS >  Key names narrow to properties names of other object in TypeScript
Key names narrow to properties names of other object in TypeScript

Time:12-21

I want to do my code better. I have this one:

interface MyInterface {
  propertyOne: string;
  propertyTwo: string;
}

type MyProps = 'propertyOne' | 'propertyTwo'; // repeating names !!!

I need get type included name of MyInterface properties. Exists something like?:

type MyProps = Props<MyInterface>; // incorrect !!!

because I need to declaration narrow key names in other object:

let MyObject: { [key in MyProps]: SomeOtherInterface }; // I want to do better (without MyProps)

CodePudding user response:

Are you seeking to keyof keyword?

interface MyInterface {
  propertyOne: string;
  propertyTwo: string;
}

type Keys<T extends object> = keyof T;
type MyProps = Keys<MyInterface > ; // no repeating repeating names !!!
let MyObject: { [key in MyProps ]: string } = {
    propertyOne: 'test',
    propertyTwo: 'test'
}

Link to playground

CodePudding user response:

A simple solution is to use Record and keyof:

let myObject: Record<keyof MyInterface, SomeOtherInterface>;
  • Related