如何在打字稿中声明数字

问题描述 投票:-1回答:1

我尝试声明属性值的数字,但不起作用。如何声明它。如果有人知道,请帮助解决此问题。

let test={ 
name:'Tree',
type:'Land',
attr:{

value:Number:"12345",

content:"test"

}

}

Attr值类型应为数字。

typescript angular6 angular5
1个回答
1
投票

都错,让我修复:

let test = { 
   name = 'Tree',
   type = 'Land',
   attr = {
      value = 12345,
      content = 'test'
   }
}

初始化所有内容时,无需设置类型。


1
投票

您正在将数据类型语句与赋值混淆,如果您想拥有一个键入的json对象,则必须创建一个类

class Test{
    name:String;
    type:String;
    attr:{
        value:Number;
        content:String;
    }
}

let test: Test = {
    name: 'Tree',
    type: 'Land',
    attr: {
        value: 12345,
        content: "test"
    }
}

let test2: Test = {
    name: 'Tree',
    type: 'Land',
    attr: {
        value: "12345", // <-- this will produce a error
        content: "test"
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.