账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    使用Typescript,如何解决2个不同文件的2个类需要互相引用 来进行类型检查
    24
    0

    问题说明

    在看VSCode源码时发现存在,
    A类里会创建B类
    B类方法需要用A类实例作参数,
    ts在声明参数或变量需要定义类型,
    于是就构成了需要互相引用的问题。

    不过VSCode通过打包解决这个问题,导入时使用绝对路径。
    但是会产生一个新的问题,编辑器无法进行追踪,也就没有代码提示了

    那么是否存在什么方法既能解决互相引用,又能解决编辑器提示的问题呢?

    例子

    这个例子不是很恰当,可以通过其他的结构来实现同样的功能避免这种问题,但这里主要是为了说明我想怎么引用。

    /* parent.ts */
    import { Child } from './child'
    
    export class Parent {
        firstName: string
        lastName: string
        child: Child
        constructor(firstName: string, lastName: string, childfirstName: string) {
            this.firstName = firstName
            this.lastName = lastName
            this.child = new Child(childfirstName)
        }
        getChildName() {
            return this.child(this)
        }
    }
    /* child.ts */
    import { Parent } from './parent'
    
    export class Child {
        firstName: string
        constructor(firstName: string) {
            this.firstName = firstName
        }
        getName(parent: Parent) { // 这里引用Parent做类型检查
            return this.firstName + ' ' + parent.lastName
        }
    }
    /* test.ts */
    import { Parent } from './parent'
    
    const parent = new Parent('Jonathan', 'Joestar', 'George')
    console.log(parent.getChildName()) // George Joestar
    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 在TypeScript中,你可以使用类型系统来解决这个问题。你可以为每个类创建一个接口,这个接口包含了需要引用的类型。然后,你可以在两个文件中使用这个接口来引用彼此。

      例如,假设你有两个文件,一个是App.ts,另一个是MyComponent.tsApp.ts有一个类MyComponent,它需要App类的某个属性。你可以这样创建接口:

      typescript interface MyComponent { // 要引用的属性 }

      然后,你可以在App.ts中使用这个接口来引用MyComponent

      typescript class App { // ... myComponent = new MyComponent(); // ... }

      这样,App.ts就可以知道MyComponent类需要哪些属性,并在需要时使用这些属性。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部