简体   繁体   English

转换类类型并调用静态属性

[英]Casting a class type and calling a static property

I'm working in a javascript project using jsdoc/typescript validation and having trouble casting a type, and using a static property of it afterwards.我在一个使用jsdoc/typescript验证的 javascript 项目中工作并且在转换类型时遇到问题,然后使用它的静态属性。

When using an imported type I have the below problem:使用导入类型时,我遇到以下问题:

// @ts-check -- foo.js
export default class Foo {
    static bar() {}
}

// @ts-check -- bar.js

/** @typedef {import('./foo').default} Foo */

const HopefullyFoo = /** @type {unknown} */ ('Foo');

const foo = /** @type {typeof Foo} */ (HopefullyFoo);

foo.bar();

Output:输出:

src/components/bar.js:7:31 - error TS2693: 'Foo' only refers to a type, but is being used as a value here.

7 const foo = /** @type {typeof Foo} */ (HopefullyFoo);
                                ~~~

If I put everything in one file it seems ok:如果我将所有内容都放在一个文件中,那似乎没问题:

// @ts-check

class Foo {
    static bar() {}
}

const LikelyFoo = /** @type {unknown} */ ('Foo');

const foo = /** @type {typeof Foo} */ (LikelyFoo);

foo.bar();

// No errors

If I don't cast to typeof I get this error so I don't think that's right either.如果我不强制转换为 typeof 我会收到这个错误,所以我也不认为这是正确的。

// @ts-check

class Foo {
    static bar() {

    }
}

const LikelyFoo = Foo;

const foo = /** @type {Foo} */ (LikelyFoo);

foo.bar();

Output输出

src/components/foo.js:13:5 - error TS2576: Property 'bar' is a static member of type 'Foo'

13 foo.bar();
       ~~~

Is this possible?这可能吗?

Type of a class is a type that an object created by the constructor of this class will have.类的类型是由该类的构造函数创建的对象将具有的类型。 This type contains only instance level fields, that is why you correctly uses typeof operator.此类型仅包含实例级字段,这就是您正确使用typeof运算符的原因。 The problem is that the operator cannot be applied to type, instead it needs a value.问题是运算符不能应用于类型,而是需要一个值。 In case of usual import一般进口的情况

import Foo from "./foo";

you get both the type and the value (constructor) but in case of jsdoc import you get a type only.您同时获得类型和值(构造函数),但在 jsdoc 导入的情况下,您只能获得一个类型。 So if you cannot import the real value for some reason you may add an alias for typeof Foo next to the class definition:因此,如果由于某种原因无法导入实际值,则可以在类定义旁边为typeof Foo添加别名:

foo.js foo.js

// @ts-check -- foo.js
export default class Foo {
  static bar() {}
}
/** @typedef {typeof Foo} FooCtor */

and use it then然后使用它

// @ts-check -- bar.js

/** @typedef {import('./foo').FooCtor} FooCtor */

const HopefullyFoo = /** @type {unknown} */ ('Foo');

const foo = /** @type {FooCtor} */ (HopefullyFoo);

foo.bar();

PS: tbh, I've never seen uses TS this way, so I may be wrong. PS:tbh,我从未见过以这种方式使用 TS,所以我可能是错的。

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

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