Website-Suche

TypeScript - Generischer Typ, der die Eigenschaften eines anderen Typs großschreibt?


Ich versuche, einen generischen Typ zu erstellen, der einen anderen Typ mit allen großgeschriebenen Eigenschaftsnamen darstellt. Ist das möglich?

Zum Beispiel:

type Example = {
  id: number
  name: string
  AnotherProperty: boolean
}

type CapitalizedProps<T> = ???

// CapitalizedProps<Example> = {
//   Id: number,
//   Name: string,
//   AnotherProperty: boolean
// }

Ich habe versucht:

type Example = {
  id: number
  name: string
  AnotherProperty: boolean
}

type CapitalizedProps<T> = {
  [K in Capitalize<keyof T & string>]: T[Uncapitalize<K> & keyof T]
}

const foo: CapitalizedProps<Example> = {
  Id: 1,
  name: 'foo',           // This shouldn't be allowed, but Uncapitalize<'name'> resolves to 'name'.
  AnotherProperty: true, // Type 'boolean' is not assignable to type 'never'.ts(2322)
}                        //   (expects property to be "anotherProperty")

und :

type CapitalizedProps<T> = {
  [K in Capitalize<keyof T & string>]: T[keyof T]
}

const foo: CapitalizedProps<Example> = {
  Id: 1,
  Name: 1337,             // This shouldn't be allowed, but T[keyof T] resolves
  AnotherProperty: true,  //   to the union of all types for all properties in T.
}

Antwort #1

Der Trick besteht darin, die Tastenbelegung zu ändern. Es sollte so aussehen:

type CapitalizedProps<Type> = {
    [Property in keyof Type as Capitalize<string & Property>]: () => Type[Property]
};