简体   繁体   English

为什么TypeScript的方法需要一个变量作为返回类型?

[英]why does TypeScript's method need a variable as return type?

I'm new to typescript, forgive me if the question is stupid. 我是打字稿新手,如果问题很愚蠢,请原谅我。

For the following code: 对于以下代码:

import { Component, ViewChild } from '@angular/core';
//....
export class MyApp {

  @ViewChild(Nav) nav: Nav;
//....

I understand that Nav is the return type, but what does "nav: Nav" means? 我知道Nav是返回类型,但是“ nav:Nav”是什么意思? why does a return type need a "nav" as a variable? 为什么返回类型需要“ nav”作为变量? I tried to look at the official document but didn't find a clue(perhaps I barked up to the wrong trees) does this equivalent to: 我试图查看正式文档,但没有找到线索(也许我吠叫到错误的树上)等同于:

import { Component, ViewChild } from '@angular/core';
//....
export class MyApp {

  @ViewChild(nav: Nav) Nav;
//....

This actually looks like a property (not a method) of the class called nav , of type Nav , which is decorated by ViewChild . 实际上,这看起来像是Nav类型的称为nav的类的属性(不是方法),由ViewChild装饰。 Putting in on one line makes it a little confusing I think. 放在一条线上会使我感到有些困惑。 It's easier to see what its doing this way: 可以更容易地看到它的这种方式:

import { Component, ViewChild } from '@angular/core';
//....
export class MyApp {

  @ViewChild(Nav)
  nav: Nav;
//....

You can read about decorators here . 您可以在此处阅读有关装饰器的信息 You can decorate classes, properties, or methods, and decorators use the @decoratorName syntax, much like they do in other languages. 您可以装饰类,属性或方法,并且装饰器使用@decoratorName语法,就像它们在其他语言中一样。

EDIT: 编辑:

To be a little clearer, in this case ViewChild is a decorator factory , bascially a function that returns a decorator. 为了更清楚一点,在这种情况下, ViewChild是一个装饰器工厂ViewChild是一个返回装饰器的函数。 So you give this function Nav as an argument (which means that Nav is a class constructor function, I presume), and it returns the actual decorator. 因此,您将此函数Nav作为参数(我想是Nav是一个类构造函数),它返回实际的装饰器。

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

相关问题 当您将返回类型方法的 output 分配给变量时,为什么 Typescript 无法推断类型? - Why Typescript can't infer type when you assign a return typed method's output to a variable? 类型返回null的方法返回类型 - Method return type with null in typescript 为什么打字稿无视变量类型? - Why is typescript disregarding a variable type? 在angular2打字稿方法中指定返回类型 - Specifying return type in a angular2 typescript method 如何在 TypeScript 中正确更改变量的类型? - How to properly change a variable's type in TypeScript? 为什么我们在使用 Angular CRUD 操作时需要在 get/post 方法中提及返回类型? - Why we need to mentions return type in get/post method while using Angular CRUD operation? 为什么打字稿接受数字值作为类型? - Why does typescript accept a number value as a type? 为什么 TypeScript 接受值作为数据类型? - Why does TypeScript accept value as a data type? 如何在离子打字稿文件中的方法中返回字符串并分配给变量? - How to return a string in a method in an ionic typescript file and assign to a variable? 如何告诉Typescript在这种情况下*函数的返回类型永远不会为null - How to tell Typescript that *in this instance* a function's return type is never null
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM