如何在打字稿中导入嵌套接口

发布于 2025-01-30 18:49:41 字数 863 浏览 2 评论 0原文

IT打字稿导入嵌套接口时,VS代码中的preadiveatext在高级接口中显示我的项目,但在嵌套的界面中不显示。

“示例”接口中有一个[key:string]意味着我不能将PredivateTatext用于此类数据结构(即使它将检查类型安全性),或者它只是无法正常设置它。

示例

export interface Item {
    id: number;
    size: number;
}
export interface Example {
    name: string;
    items: {
        [key: string]: Item
    };
}

然后file 2

import {Example, Item} from '../utils/interfaces'

const obj = {
    name: "test",
    items: {
        "a": {
            id: 1,
            size: 10
        },
        "b": {
            id: 2,
            size: 34
        }
    }
}

结果,

proadiCterText适用于第一个级接口,但在此之后不做

console.log(obj.            // predictatext offers two options: items & names
console.log(obj.items.      // predictatext offers :    NOTHING

It Typescript when I import nested interfaces the predictatext in VS code shows me items in the high level interface but not in the nested one.

There is a [key:string] in the "Example" interface does this mean I cannot use the predictatext for data structures of this sort (even though it will check type safety), or is it just not working as I have set it up incorrectly.

Example

export interface Item {
    id: number;
    size: number;
}
export interface Example {
    name: string;
    items: {
        [key: string]: Item
    };
}

Then file 2

import {Example, Item} from '../utils/interfaces'

const obj = {
    name: "test",
    items: {
        "a": {
            id: 1,
            size: 10
        },
        "b": {
            id: 2,
            size: 34
        }
    }
}

RESULT

The predictertext works for the first level interface but not after that eg

console.log(obj.            // predictatext offers two options: items & names
console.log(obj.items.      // predictatext offers :    NOTHING

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风蛊 2025-02-06 18:49:41

问题不是嵌套接口。以下内容也不会自动完成:

interface Example {
   [key: string]: number
}

不能自动完成,因为键可能是任何东西。同样,obj.items。之后的任何内容都是有效的。

如果仅允许某些项目,则必须在接口中指定它们。

The problem isn't the nested interfaces. The following won't autocomplete either:

interface Example {
   [key: string]: number
}

It can't autocomplete because the key could be anything. Similarly, anything after obj.items. is valid.

If only certain items are allowed, you would have to specify them in the interface.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文