为什么自动完成停止在 TypeScript 类型的对象中工作? [英] Why autocomplete stop working in an object with type in TypeScript?

查看:21
本文介绍了为什么自动完成停止在 TypeScript 类型的对象中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个对象中有一个路由列表,我想将它导入到另一个文件中,并自动完成对象属性.

I have a list of routes in one object and want to import it in other file and have autocomplete for object properties.

index.ts

import allRoutes from './routes';

allRoutes.routeHome;

routes.ts

const allRoutes = {
  routeHome: '',
  routePortfolio: 'portfolio'
};

export default allRoutes; 

一切正常.但是,如果我将类型添加到我的 allRoutes 以进行这样的类型检查:

All works fine. But if I add types to my allRoutes for some typecheking like this:

const allRoutes: {[key: string]:string} = {
  routeHome: '',
  routePortfolio: 'portfolio'
};

或者像这样:

interface IRoutes {
    [key: string]: string;
}

const allRoutes: IRoutes = {
    routeHome: '',
    routePortfolio: 'portfolio'
};

一切都崩溃了

我在 WebStorm 或 VSCode 中尝试过.如果我为对象属性添加类型 - 自动完成停止工作.为什么会发生?我该如何解决这个问题?

I try this in WebStorm or VSCode. If I add a type for object properties - autocomplete stops working. Why does it happen? And how I can fix this?

推荐答案

一旦用类型 { [key: string]: string } 初始化常量,原始类型就丢失了.如果您想保留原始类型但检查它是否可分配给 { [key: string]: string },您可以这样做:

Once you initialize the constant with type { [key: string]: string }, the original type is lost. If you want to preserve the original type but check that it is assignable to { [key: string]: string }, you can do this:

function asStrings<T extends { [key: string]: string }>(arg: T): T {
  return arg;
}

const allRoutes = asStrings({
  routeHome: '',
  routePortfolio: 'portfolio'
});

有一个不需要调用函数的解决方案的建议.

There is a suggestion for a solution that would not require calling a function.

这篇关于为什么自动完成停止在 TypeScript 类型的对象中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆