Answer the question
In order to leave comments, you need to log in
[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"?
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"
}
}
type T1 = {
channelID: string
content: string
}
type T2 = {
messageID: string
}
Answer the question
In order to leave comments, you need to log in
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}
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 questionAsk a Question
731 491 924 answers to any question