简体   繁体   English

Typescript 导出推断类型而不是显式类型

[英]Typescript export inferred type instead of explicit type

My context is within vue-router , though that's probably not important我的上下文在vue-router中,尽管这可能并不重要

I would like to define my routes like this我想像这样定义我的路线

import { RouteLocationRaw } from 'vue-router'

type RouteNames = 'dashboard' | 'flowRun'
type RouteProperties = Record<RouteNames, (...param:string[]) => RouteLocationRaw>

const Route: RouteProperties = {
    dashboard: () => ({ name: 'dashboard' }),
    flowRun: (flowRunId: string) => ({name: 'flow-run', params: {flowRunId}})
} as const

however, when I go to use this my types are using the explicit RouteProperties , which is actually worse than it would be if I let typescript infer the types.但是,当我 go 使用它时,我的类型正在使用显式RouteProperties ,这实际上比让 typescript 推断类型更糟糕。 If I import Routes and type Routes.flowRun , all I see for params is ...params:string[] which makes sense since that's how I explicitly defined it.如果我导入 Routes 并输入Routes.flowRun ,我看到的所有参数都是...params:string[]这是有道理的,因为这就是我明确定义它的方式。

If I instead define my routes as如果我改为将我的路线定义为

const Route = {
    dashboard: () => ({ name: 'dashboard' }),
    flowRun: (flowRunId: string) => ({name: 'flow-run', params: {flowRunId}})
} as const

now when I import Routes, and use Routes.flowRun , my parameter is named with an explicit type and will not let me call without providing the param.现在,当我导入 Routes 并使用Routes.flowRun时,我的参数以显式类型命名,并且在不提供参数的情况下不会让我调用。

Is it possible to have the type safety of my explicit types when defining new routes, but still export as the inferred types for a better type safety when used?在定义新路由时是否可以具有我的显式类型的类型安全性,但在使用时仍然导出为推断类型以获得更好的类型安全性?

Yes, by using an identity function.是的,通过使用身份 function。 The generic constraint will enforce that the input value extends the constraint, but will return the actual type of the input value:通用约束将强制输入值扩展约束,但将返回输入值的实际类型:

TS Playground TS游乐场

import { RawLocation } from 'vue-router';
type RouteLocationRaw = RawLocation;

type RouteNames = 'dashboard' | 'flowRun';
type RouteProperties = Record<RouteNames, (...param:string[]) => RouteLocationRaw>;

function typeSafeRouteProps <T extends RouteProperties>(value: T): T {
  return value;
}

const Route = typeSafeRouteProps({
  dashboard: () => ({ name: 'dashboard' }),
  flowRun: (flowRunId: string) => ({name: 'flow-run', params: {flowRunId}}),
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM