如何在Typescript中定义对象变量的类型? [英] How can I define the types of an object variable in Typescript?

查看:3652
本文介绍了如何在Typescript中定义对象变量的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在类 a 中有这个对象变量:

I have this object variable in the class a:

class a {
  abc = {
    def: number = 22  // won't work
  }
  ghi: number = 23; // works

..

我如何定义(内联而不使用接口)对象内的变量 def 的类型 abc

How can I define (inline without using an interface) the type of the variable def that is inside the object abc?

我尝试使用这种语法但它不会接受它。

I tried using this syntax but it will not accept it.

推荐答案

它可能是 - 使用断言和内联声明:

The way it could be - is to use assert and inlined declaration:

class MyClass {
  abc = <{ def : number }>{
    def: 1,
  };  
}

相同,但显性界面更具可读性

The same, but a bit more readable with explicit interface

interface IMyObject{
  def : number 
}

class MyClass1 {
  abc = <IMyObject>{
    def: 1,
  };  
}

检查这里

为什么会这样?

class a {
  abc = {
    def: number = 22  // won't work
  }
  ghi: number = 23; // works

因为ghi是a类的成员/属性 - 所以就像这样:

because the ghi is the member/property of class a - so it is just like this:

class MyClass {
  // standard way how to define properties/members of a class
  public obj: number;
  private other: string;
}

这篇关于如何在Typescript中定义对象变量的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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