- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个简单的函数断言一个对象是一个类的实例。对象和类都作为参数传递给函数。
以下是一个说明问题的简化示例(没有深入了解真实代码的本质):
function verifyType<T>(instance: unknown, classType:new () => T):instance is T {
if (!(instance instanceof classType)) throw(`Expecting instance of ${classType.name}`);
return true;
}
( TypeScript Playground link )
此函数适用于大多数类:
class Foo {
constructor() {
}
}
const foo:unknown = new Foo();
verifyType(foo, Foo);
// OK
但是,如果该类具有私有(private)构造函数,我会收到编译器错误。
我理解其中的原因,这是有道理的。构造函数类型意味着调用代码可以构造类,而私有(private)构造函数意味着不允许这样做。
但是,我找不到仍然允许我使用 instanceof
的替代方案:
class Bar {
private constructor() {
}
static create() {
return new Bar();
}
}
const bar:unknown = Bar.create();
verifyType(bar, Foo);
// OK
verifyType(bar, Bar);
// Argument of type 'typeof Bar' is not assignable to parameter of type 'new () => Bar'.
// Cannot assign a 'private' constructor type to a 'public' constructor type.
T extends typeof Object
我读了How to refer to a class with private constructor in a function with generic type parameters?
根据对那个问题的回答,我想也许我可以使用以下内容:
function verifyType<T extends typeof Object>(instance: unknown, classType:T):instance is InstanceType<T>
但是,由于 Object
的许多静态方法,这似乎会引发错误:
const foo = new Foo();
verifyType(foo, Foo);
// Argument of type 'typeof Foo' is not assignable to parameter of type 'ObjectConstructor'.
// Type 'typeof Foo' is missing the following properties from type 'ObjectConstructor': getPrototypeOf, getOwnPropertyDescriptor, getOwnPropertyNames, create, and 16 more.
我在 typeof Object
上尝试了很多变体,看看我是否既能满足 TypeScript 又能确保运行时的正确性,包括:
function verifyType<T extends Function & Pick<typeof Object, "prototype">>(instance: unknown, classType:T):instance is InstanceType<T>
然而,虽然这解决了编译时错误,但它似乎是通过允许在运行时失败的类型来实现的,这是 Not Acceptable :
verifyType(bar, ()=>{});
// No compile-time errors
// Runtime Error: Function has non-object prototype 'undefined' in instanceof check
//@ts-expect-error
,你是我唯一的希望最后,这可能是一个过于小众的用例,我可能不得不接受这种边缘情况不会很快得到支持并相应地免除我的代码。
// @ts-expect-error Unfortunately, TS has no type representing a generic class with a private constructor
verifyType(bar, Bar);
最佳答案
我建议的方法是对 classType
参数的 prototype
属性进行推断,如下所示:
function verifyType<T extends object>(
instance: unknown,
classType: Function & { prototype: T }
): asserts instance is T {
if (!classType.prototype) throw (
`Wait, ${classType.name || "that"} is not a class constructor`);
if (!(instance instanceof classType)) throw (
`Expecting instance of ${classType.name}`);
}
一般来说,如果 y
是某种函数类型,TypeScript 会让您编写 x instanceof y
,因此 Function &
,然后我们推断 generic类型参数 T
对应于 classType
的实例类型,通过说它是 prototype
属性的类型(TypeScript 将类构造函数原型(prototype)建模为与类实例的类型相同,尽管在实践中通常并非如此。有关更多信息,请参阅 microsoft/TypeScript#44181 以及其他可能)。
除了 Function & {protoype: T}
之外,我还对您的代码进行了一些更改:
verifyType()
现在是 assertion function返回 asserts instance is T
而不是 type guard function返回 实例是 T
。类型保护函数应该返回 true
或 false
并且编译器在其 control flow analysis 中使用它.另一方面,断言函数不返回任何值,它们只是确保可缩小的东西确实缩小了。如果你有一个总是返回 true
(否则抛出异常)的类型保护函数,那么你可能需要一个断言函数。
我在主体内部进行了显式检查,以查看是否定义了 classType.prototype
。 TypeScript 为 Function
提供了 the any
type 的 prototype
属性而不是更安全的 unknown
type ,不幸的是,这几乎不可能检测到像 ()=>{}
这样的非构造函数在成为 instanceof
的目标时会抛出运行时错误。那么,我没有尝试在类型系统中表示它,而是尝试强化 verifyType()
的实现以应对此类边缘情况。您可能需要检查 (!classType.prototype || typeof classType.prototype !== "object")
或您认为必要的任何其他逻辑。
让我们测试一下:
class Foo {
constructor() {
}
a = 1;
}
const foo: unknown = new Foo();
foo.a // error! Object is of type unknown
verifyType(foo, Foo);
foo.a // okay
console.log(foo.a.toFixed(1)) // "1.0"
看起来不错,编译器在调用 verifyType(foo, Foo)
之后(但不是之前)看到 foo
是一个 Foo
.
class Bar {
private constructor() {
}
static create() {
return new Bar();
}
b = "z"
}
const bar: unknown = Bar.create();
verifyType(bar, Bar);
console.log(bar.b.toUpperCase()); // "Z"
看起来也不错。编译器很乐意允许 verifyType(bar, Bar)
因为 Bar
有一个类型为 Bar
的 prototype
属性(在编译器看来是这样的),因此您可以访问 Bar
的 b
属性。 Bar
有一个 private
构造函数并不重要。
最后:
const baz: unknown = new Date();
verifyType(baz, () => { }); // 💥 Wait, that is not a class constructor
baz // any
我们无法在编译时标记 verifyType(baz, ()=>{})
,但至少你会得到一个有意义的运行时错误,因此随后的“缩小”baz
从 unknown
到 any
(呃,谢谢 any
)不会影响我们。
关于typescript - 表示具有私有(private)构造函数的泛型类的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74185545/
我已经写了并且 npm 发布了这个:https://github.com/justin-calleja/pkg-dependents 现在我正在用 Typescript 编写这个包:https://g
我有一个函数,我想在 TypeScript 中模拟它以进行测试。在我的测试中,我只关心 json和 status .但是,当使用 Jest 的 jest.spyOn 时我的模拟函数的类型设置为返回 h
我正在使用一个库 (Axios),它的包中包含 Typescript 声明。 我想声明一个将 AxiosResponse(在库的 .d.ts 文件中声明)作为参数的函数。我有以下内容: functio
我是 Typescript 的新手。我想使用 将一个 Typescript 文件加载到另一个 Typescript 文件中标签。 我做了一些事情,但它不起作用!请帮助我。 first.ts: imp
为什么我会收到下面屏幕截图中显示的错误? Atom 说我的 tsconfig.json“项目文件包含无效选项”用于 allowJs、buildOnSave 和 compileOnSave。 但是应该允
所以我正在创建一个 TypeScript 库,我可以轻松地将所有生成的 JS 文件编译成一个文件。有没有办法将所有 .ts 和 .d.ts 编译成一个 .ts 文件? 除了支持 JS 的版本(较少的智
Microsoft Research 提供了一种名为Safer TypeScript 的新 TypeScript 编译器变体: http://research.microsoft.com/en-us/
我需要这个来在单个文件中分发 TypeScript 中的库。有没有办法将多个 typescript 文件合并到(一个js文件+一个 typescript 定义)文件中? 最佳答案 要创建一个库,您可以
用例:我想知道一个函数在 typescript 中执行需要多少时间。我想为此目的使用装饰器。我希望装饰器应该返回时间以便(我可以进一步使用它),而不仅仅是打印它。 例如: export functio
我想检查一个类型是否可以为 null,以及它是否具有值的条件类型。 我尝试实现 type IsNullable = T extends null ? true : false; 但是好像不行 type
我的问题是基于这个 question and answer 假设我们有下一个代码: const myFn = (p: { a: (n: number) => T, b: (o: T) => v
我知道双重否定前缀,我知道 TypeScript 的单后缀(非空断言)。 但是这个双后缀感叹号是什么? /.*验证码为(\d{6}).*/.exec(email.body!!)!![1] 取自here
我正在使用以下文件结构在 Webstorm 中开发一个项目 | src | ... | many files | types | SomeInterface |
在 TypeScript 类中,可以为属性声明类型,例如: class className { property: string; }; 如何在对象字面量中声明属性的类型? 我试过下面的代码,但它
我正在寻找一种在不丢失推断类型信息的情况下将 TypeScript 中的文字值限制为特定类型的好方法。 让我们考虑一个类型Named,它保证有一个名字。 type Named = { name:
在 TypeScript 中,我想创建一个联合类型来表示属于一个或多个不同类型的值,类似于 oneOf在 OpenAPI或 JSON Schema .根据a previous answer on a
type Func = (foo:string) => void // function expression const myFunctionExpression:Func = function(f
假设我有一个联合类型,我正在使用类似 reducer 的 API 调用模式,看起来像这样: type Action = { request: { action: "create
我在 typescript 中有以下去抖功能: export function debounce( callback: (...args: any[]) => void, wait: numb
在 Vue3 的 defineComponent 函数中,第一个泛型参数是 Props,所以我在这里使用 Typescript 接口(interface)提供我的 props 类型。喜欢: expor
我是一名优秀的程序员,十分优秀!