Home > front end >  TypeScript: Restrict keyof type
TypeScript: Restrict keyof type

Time:01-26

interface StorageType {
    [key: string]: StorageType | string | number
}

interface StorageSchema extends StorageType {
    username: string,
    user: {
        name: string,
        age: number,
        address?: {
            street: string,
            aptNumber: number,
        },
    },
    email: string,
    totalItems: number,
};

type InputType =  keyof StorageSchema;

How do I restrict InputType to only for key of StorageSchema and not any string.

CodePudding user response:

You can extract the known keys of a type using a mapped type:

type InputType =  keyof {
    [P in keyof StorageSchema as string extends P? never: P] : unknown
};

Playground Link

The as clause will go though all the fields and indexes on a type and pass them through the conditional type. string extends P will only be true for string, so that will be mapped to never meaning it will be removed from the resulting type. The other keys will remain unaffected and we can use keyof to get them from the mapped type.

CodePudding user response:

type InputType =  keyof {
    [P in keyof StorageSchema as string extends P? never: P] : unknown
};
  • Related