1

I am writing a type for nested routes array. The array can contain either a prefixed routes object or a simple route object.

The conditions are:

  1. If it is a simple route object, then it must contain only the properties that are mentioned in IApiRoute.
  2. If it is a prefixed route object that it must contain two keys only
    2 a. First key is prefix as mentioned in IPrefixApiRoute.
    2 b. Second key is routes array, it can contain an array of objects mentioned in point 2 and point 1.

I have created the typings, but there is a problem, it is not giving a compile time error if I create an object like this

const array: Array<IRawApiRoute> = [
    {
        prefix: "auth",
        routes: [],
        method: "GET", // This key shouldn't be allowed here, as this object can contain only the keys from IPrefixApiRoute
    },
];

The typings that I have prepared are:

type Method = "GET" | "DELETE" | "HEAD" | "OPTIONS" | "POST" | "PUT" | "PATCH";

interface IApiRoute {
    route: string;
    method: Method;
    routeParams: string[];
    queryParams: string[];
    name: string;
}

interface IPrefixApiRoute {
    prefix: string;
    routes: Array<IRawApiRoute>;
}

type IRawApiRoute = IApiRoute | IPrefixApiRoute;

I can't seem to figure out the problem. Any help would be appreciated. Thanks

Muhammad Waqar
  • 108
  • 2
  • 8
  • One more thing that I just noticed, you can also create an object and put all the combined keys from `IApiRoute` and `IPrefixApiRoute` in that object and it happily be added in the `Array` without any complaints :( – Muhammad Waqar Dec 17 '22 at 15:28
  • Looks like my whole life was a lie https://www.typescriptlang.org/play?ts=4.7.4#code/JYOwLgpgTgZghgYwgAgJIGcD2AbOkAmAwpuHKNMgN4BQydywWuBAanNgK4QBcy6YUUAHMA3NQC+1aqEixEKAIIhMYABbQMOPBCIkwZEBRr1kcZWo1Nt+Npx58BwsZOoIS-ZJAC2AB16bmHWJScihkAB9kJRV1KADrYP1Q5ABeKlp6Ri1Wdi5eACJUUy9kWIh8gBoMujMYy2ydWzzkfIAJTAB3YrRS6AgAfn6AQhH8iREgA – Muhammad Waqar Dec 17 '22 at 15:50
  • The way to actually prohibit a property is by making it an optional property of type `never`, as shown [here](https://tsplay.dev/WkOaJW). See the linked question and answer for more information about why this is happening – jcalz Dec 17 '22 at 18:59

0 Answers0