Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

How rename certain keys for a Typescript type

I need to rename some properties / keys of a certain Typescript type for a specific React component.

My Props type looks like this:

export type Props = {
  data: {
    title: string;
    items: (VarianOne | VariantTwo)[];
  };
}

VariantOne (and VariantTwo) are referring to other types (defined in another file):

export type VariantOne = { __typename: 'VariantOne' } & VariantOneItem;

Inside VariantOneItem I want to change both key names myAlias to e.g renamedAlias and anotherAlias to renamedAnotherAlias:

export interface VariantOneItem {
  myAlias: string;
  anotherAlias: string;

}

I started with the following approach (for one key now), but it's not working yet:

export type Props = {
      data: {
        title: string;
        items: (VarianOne | VariantTwo)[];
      };
    } & RenamedVariantOne;

type RenamedVariantOne = Omit<VariantOne, 'myAlias'> & { renamedAlias: VariantOne['myAlias'] };
question from:https://stackoverflow.com/questions/65858173/how-rename-certain-keys-for-a-typescript-type

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
type SomeData = {
    prop1: string;
    prop2: number;
}

type WithChange<T> = { [P in keyof T & string as `${P}Change`]: T[P] };

type SomeMoreData = WithChange<SomeData>; // {  prop1Change: string, prop2Change: number }

Here is what you can do.

type SomeMoreDataMapping = {
  prop1: "prop1Change"
  prop2: "prop2Change"
}

type ValueOf<T> = T[keyof T]
type KeyValueTupleToObject<T extends [keyof any, any]> = {
  [K in T[0]]: Extract<T, [K, any]>[1]
}
type MapKeys<T, M extends Record<string, string>> =
  KeyValueTupleToObject<ValueOf<{
    [K in RequiredKeys<T>]-?: [K extends keyof M ? M[K] : K, T[K]]
  }>> & Partial<KeyValueTupleToObject<ValueOf<{
    [K in OptionalKeys<T>]-?: [K extends keyof M ? M[K] : K, T[K]]
  }>>> extends infer O ? { [K in keyof O]: O[K] } : never;

type RequiredKeys<T> = { [K in keyof T]-?: {} extends Pick<T, K> ? never : K }[keyof T];
type OptionalKeys<T> = { [K in keyof T]-?: {} extends Pick<T, K> ? K : never }[keyof T];

interface SomeData {
  prop1?: string;
  prop2: number;
  prop3?: string;
  prop4: number;
}

type SomeMoreData = MapKeys<SomeData, SomeMoreDataMapping>;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...