25

I have a nested object of translation strings like so:

viewName: {
    componentName: {
        title: 'translated title'
    }
}

I use a translation library that accepts strings in dot notation to get strings, like so translate('viewName.componentName.title').

Is there any way I can force the input parameter of translate to follow the shape of the object with typescript?

I can do it for the first level by doing this:

translate(id: keyof typeof languageObject) {
    return translate(id)
}

But I would like this typing to be nested so that I can scope my translations like in the example above.

0

4 Answers 4

65

UPDATE for TS4.1. String concatenation can now be represented at the type level through template string types, implemented in microsoft/TypeScript#40336. Now you can take an object and get its dotted paths right in the type system.

Imagine languageObject is this:

const languageObject = {
    viewName: {
        componentName: {
            title: 'translated title'
        }
    },
    anotherName: "thisString",
    somethingElse: {
        foo: { bar: { baz: 123, qux: "456" } }
    }
}

First we can use recursive conditional types as implemented in microsoft/TypeScript#40002 and variadic tuple types as implemented in microsoft/TypeScript#39094 to turn an object type into a union of tuples of keys corresponding to its string-valued properties:

type PathsToStringProps<T> = T extends string ? [] : {
    [K in Extract<keyof T, string>]: [K, ...PathsToStringProps<T[K]>]
}[Extract<keyof T, string>];

And then we can use template string types to join a tuple of string literals into a dotted path (or any delimiter D:)

type Join<T extends string[], D extends string> =
    T extends [] ? never :
    T extends [infer F] ? F :
    T extends [infer F, ...infer R] ?
    F extends string ? 
    `${F}${D}${Join<Extract<R, string[]>, D>}` : never : string;    

Combining those, we get:

type DottedLanguageObjectStringPaths = Join<PathsToStringProps<typeof languageObject>, ".">
/* type DottedLanguageObjectStringPaths = "anotherName" | "viewName.componentName.title" | 
      "somethingElse.foo.bar.qux" */

which can then be used inside the signature for translate():

declare function translate(dottedString: DottedLanguageObjectStringPaths): string;

And we get the magical behavior I was talking about three years ago:

translate('viewName.componentName.title'); // okay
translate('view.componentName.title'); // error
translate('viewName.component.title'); // error
translate('viewName.componentName'); // error

Amazing!

Playground link to code


Pre-TS4.1 answer:

If you want TypeScript to help you, you have to help TypeScript. It doesn't know anything about the types of concatenated string literals, so that won't work. My suggestion for how to help TypeScript might be more work than you'd like, but it does lead to some fairly decent type safety guarantees:


First, I'm going to assume you have a languageObject and a translate() function that knows about it (meaning that languageObject was presumably used to produce the particular translate() function). The translate() function expects a dotted string representing list of keys of nested properties where the last such property is string-valued.

const languageObject = {
  viewName: {
    componentName: {
      title: 'translated title'
    }
  }
}
// knows about languageObject somehow
declare function translate(dottedString: string): string;
translate('viewName.componentName.title'); // good
translate('view.componentName.title'); // bad first component
translate('viewName.component.title'); // bad second component
translate('viewName.componentName'); // bad, not a string

Introducing the Translator<T> class. You create one by giving it an object and a translate() function for that object, and you call its get() method in a chain to drill down into the keys. The current value of T always points to the type of property you've selected via the chain of get() methods. Finally, you call translate() when you've reached the string value you care about.

class Translator<T> {
  constructor(public object: T, public translator: (dottedString: string)=>string, public dottedString: string="") {}

  get<K extends keyof T>(k: K): Translator<T[K]> {    
    const prefix = this.dottedString ? this.dottedString+"." : ""
    return new Translator(this.object[k], this.translator, prefix+k);
  }

  // can only call translate() if T is a string
  translate(this: Translator<string>): string {
    if (typeof this.object !== 'string') {
      throw new Error("You are translating something that isn't a string, silly");
    }
    // now we know that T is string
    console.log("Calling translator on \"" + this.dottedString + "\"");
    return this.translator(this.dottedString);
  }
}
    

Initialize it with languageObject and the translate() function:

const translator = new Translator(languageObject, translate);

And use it. This works, as desired:

const translatedTitle = translator.get("viewName").get("componentName").get("title").translate();
// logs: calling translate() on "viewName.componentName.title"

And these all produce compiler errors, as desired:

const badFirstComponent = translator.get("view").get("componentName").get("title").translate(); 
const badSecondComponent = translator.get("viewName").get("component").get("title").translate(); 
const notAString = translator.get("viewName").translate();

Hope that helps. Good luck!

Sign up to request clarification or add additional context in comments.

20 Comments

Impressive solution! Even though the syntax becomes a bit more complex, it does the job.
It depends on exactly what you're looking for; all paths to all properties even in a recursive tree-like object? excluding paths with non-dottable properties? It's hard to figure this out in a comment section of a different question. You might want something like this but I'm not sure. Or you might want to just ask a new question. Good luck!
@BjørnEgil thanks; I modified my code above to use Extract<R, string[]>. Looks like the release version of 4.1 also needs this.
When I first worked on that, (when TS4.1 was still in development) I think there were no types like `${string}.${string}` (i.e., before microsoft/TypeScript#40598) , so Join<[string, string], '.'> would have produced just string anyway... my code bailed out early rather than recurse for the same result. It's fine to make the change you're suggesting.
@user5480949 Like this maybe? Comments sections on old answers are not the ideal place to get followup answers, so if you continue to have questions you might want to make your own post.
|
10

I made an alternative solution:

type BreakDownObject<O, R = void> = {
  [K in keyof O as string]: K extends string
    ? R extends string
      ? ObjectDotNotation<O[K], `${R}.${K}`>
      : ObjectDotNotation<O[K], K>
    : never;
};

type ObjectDotNotation<O, R = void> = O extends string
  ? R extends string
    ? R
    : never
  : BreakDownObject<O, R>[keyof BreakDownObject<O, R>];

Which easily can be modified to also accept uncompleted dot notation strings. In my project we use this to allow/deny translation object properties.

type BreakDownObject<O, R = void> = {
  [K in keyof O as string]: K extends string
    ? R extends string
      // Prefix with dot notation as well 
      ? `${R}.${K}` | ObjectDotNotation<O[K], `${R}.${K}`>
      : K | ObjectDotNotation<O[K], K>
    : never;
};

Which then can be used like this:

const TranslationObject = {
  viewName: {
    componentName: {
      title: "translated title"
    }
  }
};

// Original solution
const dotNotation: ObjectDotNotation<typeof TranslationObject> = "viewName.componentName.title"

// Modified solution
const dotNotations: ObjectDotNotation<typeof TranslationObject>[] = [
  "viewName",
  "viewName.componentName",
  "viewName.componentName.title"
];

Comments

7

@jcalz 's answer is great.

If you want to add other types like number | Date:

You should replace the first line of

type PathsToStringProps<T> = T extends string ? [] : {
    [K in Extract<keyof T, string>]: [K, ...PathsToStringProps<T[K]>]
}[Extract<keyof T, string>];

with this

type PathsToStringProps<T> = T extends (string | number | Date) ? [] : {

1 Comment

I replaced (string | number | Date) with (string | number | Date | boolean | bigint | Array<any>) to support all basic TS types
0

If the aim it to provide auto-completion, the only way I could think of providing this would be to create a type to limit what strings are allowable:

type LanguageMap = 'viewName.componentName.title' | 'viewName.componentName.hint';

function translate(id: LanguageMap) {
    return translate(id)
}

You wouldn't be able to automatically generate this using your keyof trick as the nesting would prevent that.

An alternate would be to remove the nesting, in which case your keyof trick creates the language map type for you:

let languageObject = {
    'viewName.componentName.title': 'translated title',
    'viewName.componentName.hint': 'translated hint'
};

function translate(id: keyof typeof languageObject) {
    return translate(id)
}

But I know of no way to get the best of both worlds as there is a logical break between the nesting on the one hand, and the key names on the other.

1 Comment

Yes, a flat object is what I'm using succesfully today. The nested translation object was something I was reaching for to improve the structure of my translations file. However, listing every possible path is not a quialified solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.