V
V
Vlad2021-05-15 18:12:15
typescript
Vlad, 2021-05-15 18:12:15

[TypeScript] Is it possible to create a type from the keys of an object?

Is it possible to make the types T1 and T2 contain such object-based "keys"?


There is this code:
type Args = {
    [key: string]: {
        RegExp: [string, boolean],
        description: string
    }
}
let a1: Args = {
    channelID: {
        RegExp: ["\\d+", true],
        description: "d1"
    },
    content: {
        RegExp: [".+", true],
        description: "d2"
    }
}
let a2: Args = {
    messageID: {
        RegExp: ["\\d+", true],
        description: "d1"
    }
}


Is it possible to automatically create such types based on a1 and a2 ?
type T1 = {
    channelID: string
    content: string
}
type T2 = {
    messageID: string
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2021-05-16
@TRen208

You can, if you do not explicitly specify the Args type, but then you lose the preliminary check, alas:

let a1 = {
    channelID: {
        RegExp: ["\\d+", true],
        description: "d1"
    },
    content: {
        RegExp: [".+", true],
        description: "d2"
    }
};
type T1 = {[K in keyof typeof a1]: string}

To save the check, you will have to use an additional meaningless function to qualify the type:
type Args = {
    [key: string]: {
        RegExp: [string, boolean],
        description: string
    }
}
function createArgs<T extends Args>(args: T): T {
    return args;
}

type TStringKeys<T extends Args> = {[K in keyof T]: string};


let a1 = createArgs({
    channelID: {
        RegExp: ["\\d+", true],
        description: "d1"
    },
    content: {
        RegExp: [".+", true],
        description: "d2"
    }
});

type T1 = TStringKeys<typeof a1>
Unfortunately, at the moment (ts4.2.3) it is not possible to get rid of the wrapper function.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question