4 ms·
By itself this isn't very impressive, but there's more context in the wings if you pay careful attention to the TypeScript type system. Take a look at https://g
by rictic 9y ago
By itself this isn't very impressive, but there's more context in the wings if you pay careful attention to the TypeScript type system. Take a look at https://github.com/Microsoft/TypeScript/pull/21316 https://github.com/Microsoft/TypeScript/pull/21316 and https://github.com/Microsoft/TypeScript/pull/21496 https://github.com/Microsoft/TypeScript/pull/21496. This, combined with the existing literal types and mapped types, allows the TypeScript compiler to understand a huge set of existing practices in the JavaScript world, and do high quality type inference over code that looks totally untypable.
For example, this is a pattern I see a lot:
const args = parseCliFlags({
help: {
parser: Boolean,
description: 'whether to show help',
short: 'h',
},
custom: {
parser: (v: string) => {return {hmmm: 'yes'}},
repeated: true
}
});
if (args.help) {
console.log('help screen!');
}
for (const custom of args.custom) {
console.log(custom.hmmm);
}
So we produce an args object based on the descriptors passed into parseCliFlags. Specifically, we use the parser function and the repeated field. With the above PRs, this code can be fully type checked:
interface Descriptor {
readonly parser: (value: string) => any;
readonly description?: string;
readonly short?: string;
readonly repeated?: true;
}
interface Descriptors {
readonly [flag: string]: Descriptor;
}
type FlagTypes<T> = { [K in keyof T]: FlagTypeOf<T[K]> };
type ReturnTypeOf<V> = V extends (...args: any[])=>infer R ? R : never;
type FlagTypeOf<V> = V extends {repeated: true, parser: (val: string)=> infer R} ? R[] : V extends {parser: (val: string)=> infer R} ? R : never;
That code is tricky to write, but it only needs to be written once, and submitted to DefinitelyTyped. From that point, every VSCode user could benefit from these typings (they already have this part working today, with typings for your node libraries downloaded automatically from DefinitelyTyped).