Search code examples
typescripttypestypescript-types

How to make a property inside an object a type


use typescript

I want to leave the before type below and define the after type separately.

type before = {
  title: string;
  sncFileInfoList: {
    sncFileKey1: string;
    sncFileKey2: string;
    sncFileKey3: string;
    sncFileKey4: string;
    sncFileNm: string;
  }[];
}
type after = {
  sncFileKey1: string;
  sncFileKey2: string;
  sncFileKey3: string;
  sncFileKey4: string;
  sncFileNm: string;
}

That is, I want to use the sncFileInfoList property of the before type.
The important thing is that the before type should stand still. I've tried several Utility Types that I know of, but to no avail. There is a way to disassemble the type and assemble it into an Intersection Type, but I think there will be a more elegant way.

Any help would be appreciated🙇‍♂️


Solution

  • You can use Indexed Access Types to look up a specific property on another type:

    type before = {
      title: string;
      sncFileInfoList: {
        sncFileKey1: string;
        sncFileKey2: string;
        sncFileKey3: string;
        sncFileKey4: string;
        sncFileNm: string;
      }[];
    }
    
    type after = before['sncFileInfoList'][0]
    

    TypeScript Playground