我正在try 解决如何修复这个接口,以便每个"Route"可以有一个独立的模板参数,与映射中的其他条目不同:

export type RouteMap = {
    [k in string]: Route<any>  
}

在这里,我不是真的想指定any,我希望它是推断的.有没有什么方法可以说每个条目都应该是Route<something>,但<something>可以是不同的?

这是一个应该编制的minimal example of TS Playground分.

推荐答案

TypeScrip只能推断函数中的泛型类型参数.因此,您可以使用一个只返回其参数的简单函数,同时还使用泛型类型参数约束该参数的类型,以强制TypeScrip执行此类推断:

export type RouteMap<T extends Record<string, any>> = {
    [R in keyof T]: Route<T[R]>;
}

// TypeScript can only infer generic types using function parameters
function routeMap<T extends Record<string, any>>(arg: RouteMap<T>) { return arg; }

export interface Route<P extends UriParams> {
    template: UriTemplate<P>

    get?: Handler<P>
    post?: Handler<P>
}


export type UriParams = Record<string, UrlParamValue>;
type Primitive = string | number | boolean | null;
type PrimitivePair = [key: string, value: Primitive];
type PrimitiveMap = {
    [K in string]: Primitive;
};
export type UrlParamValue = Primitive | Primitive[] | PrimitivePair[] | PrimitiveMap;

export type Handler<P extends UriParams> = (req: BunRequest<P>, res: HybridResponse) => void | Promise<void>

type HybridResponse = unknown

interface BunRequest<P extends UriParams> {
    headers: Headers
    method: unknown
    url: BunUrl<P>
    body: unknown
}


interface BunUrl<P extends UriParams> extends URL {
    params: P
    path: string
}

export class UriTemplate<P extends UriParams> {
   constructor(template: string) {
    //
   }
}

////////////////////////////////

const routes = routeMap({
    hello: {
        template: new UriTemplate<{q:Record<string,string>}>('/hello{?q*}'),
        async get(req, res) {
              // `req` is inferred as BunRequest<{q:Record<string,string>}>
        }
    }
});

TypeScript Playground

正如您所看到的,为了利用这个推断,您需要在声明它时使用routeMap函数来包装您的对象文字,以便TypeScrip正确地推断它的类型.

Typescript相关问答推荐

在Switch陈述中输入保护类

TypScript中的算法运算式

Angular 17 -如何使用新的@if语法在对象中使用Deliverc值

如何在方法中定义TypeScript返回类型,以根据参数化类型推断变量的存在?

在Angular中,如何在文件上传后清除文件上传文本框

在TypeScript中使用泛型的灵活返回值类型

有没有一种方法可以在保持类型的可选状态的同时更改类型?

将props传递给子组件并有条件地呈现它''

Angular 信号:当输入信号改变值时,S触发取数的正确方式是什么?

Vue3 Uncaught SyntaxError:每当我重新加载页面时,浏览器控制台中会出现无效或意外的令牌

TypeScrip泛型类未提供预期的类型错误

try 使Angular依赖注入工作

界面中数组中的混合类型导致打字错误

棱角分明-什么是...接口类型<;T>;扩展函数{new(...args:any[]):t;}...卑鄙?

如何通过转换器类继承使用多态将对象从一种类型转换为另一种类型

如何在本地存储中声明该类型?

如何创建一个将嵌套类属性的点表示法生成为字符串文字的类型?

完全在类型系统中构建的东西意味着什么?

可以用任意类型实例化,该类型可能与

对象只能使用 Typescript 中另一个对象的键