1

I have defined this type:

type RouteMap = { [k: string]: React.Route };

Which I am trying to apply like this:

const routes: RouteMap = {
  setDomain: { title: 'Set Domain', component: SetDomain }
};

export default class MyClass extends React.Component<void, void> {
  render() {
    return (
      <View style={styles.container}>
        <NavigatorIOS initialRoute={routes.setDomain} />
      </View>
    );
  }
}

But that is yielding this error:

Property 'setDomain' does not exist on type RouteMap.

This works if I try to access the property like so: routes['setDomain'] but i'd like to avoid that. Is there any way to let TypeScript still infer the keys from the assignment?

1 Answer 1

1

It's kind of doable with mapped types, but typescript will not infer the type in routes initializer without the help of intermediate function:

type RouteMap<K extends string> = {[T in K]: React.Route}

// dummy function necessary to infer generic type parameter from the value
function routeMap<K extends string>(r: RouteMap<K>): RouteMap<K> { return r }

const routes = routeMap({
  setDomain: { title: 'Set Domain', component: SetDomain }
});

Without routeMap() function you have to specify key type yourself, which also works but looks ugly:

const routes2: RouteMap<'setDomain'> = {
  setDomain: { title: 'Set Domain', component: SetDomain }
};
Sign up to request clarification or add additional context in comments.

Comments

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.