Skip to content

Instantly share code, notes, and snippets.

@marcolink
Created April 1, 2021 07:32
Show Gist options
  • Save marcolink/b18982dc22da96a376e0e44dbb20e5ae to your computer and use it in GitHub Desktop.
Save marcolink/b18982dc22da96a376e0e44dbb20e5ae to your computer and use it in GitHub Desktop.
Helper for localized (contentful) Entry type
/*
* https://github.com/contentful/contentful.js/blob/master/index.d.ts#L81
*/
type Entry<Fields> = {
sys: {
id: string
}
fields : Fields
}
type LocalizedFields<Fields, Locales extends keyof any> = {
[FieldName in keyof Fields]?: {
[LocaleName in Locales]?: Fields[FieldName];
}
}
type LocalizedEntry<EntryType, Locales extends keyof any> = {
[Key in keyof EntryType] :
Key extends 'fields'
? LocalizedFields<EntryType[Key], Locales>
: EntryType[Key]
}
type MyFields = {
a: string
b: number
}
type MyLocalizedEntry = LocalizedEntry<Entry<MyFields>, 'en-US' | 'de-DE'>;
const myEntry: Entry<MyFields> = {
sys: {
id: "dfsdf"
},
fields: {
a: "hello",
b: 1
}
}
const localizedEntry: MyLocalizedEntry = {
sys : {
id: 'my-id'
},
fields: {
a: {
"de-DE": 'german translation',
"en-US": 'englisch translation'
}
}
}