什么是Typescript中的new()? [英] what is new() in Typescript?

查看:1211
本文介绍了什么是Typescript中的new()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在官方文档中遇到 new() 这里

I encountered new() in the official document here about generics.

以下是代码上下文:

function create<T>(c: { new(): T; } ): T {
    return new c();
}

以上代码转换为以下JavaScript代码:

The above code is transpiled to the following JavaScript code:

function create(c) {
    return new c();
}

new()是JavaScript中的非法语法。 TypeScript是什么意思?

new() is illegal syntax in JavaScript. What does it mean in TypeScript?

此外, {new():T; } 是什么意思?我知道它必须是一种类型,但如何?

Furthermore, what does {new(): T; } mean? I know it must be a type, but how?

推荐答案

new()描述了typescript中的构造函数签名。这意味着它描述了构造函数的形状。
例如,取 {new():T; } 。你是对的它是一种类型。它是类的类型,其构造函数不带参数。请考虑以下示例

new() describes a constructor signature in typescript. What that means is that it describes the shape of the constructor. For instance take {new(): T; }. You are right it is a type. It is the type of a class whose constructor takes in no arguments. Consider the following examples

function create<T>(c: { new(): T; } ): T {
    return new c();
}

这意味着函数 create 接受一个参数,其构造函数不带参数,并返回类型 T 的实例。

What this means is that the function create takes an argument whose constructor takes no arguments and returns an instance of type T.

function create<T>(c: { new(a: number): T; } ): T

这意味着create函数接受一个参数,其构造函数接受一个数字 a 并返回类型为T. $ b的实例$ b解释它的另一种方法可以是,以下类的类型

What this would mean is that the create function takes an argument whose constructor accepts one number a and returns an instance of type T. Another way to explain it can be, the type of the following class

class Test {
    constructor(a: number){

    }
}

{new(a:number):Test}

这篇关于什么是Typescript中的new()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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