简体   繁体   English

如何在Typescript中声明具有特殊类型的变量

[英]how to declare variable with special type in Typescript

I'm loading a json file and need the fields to have the same name 我正在加载一个json文件,并且需要字段具有相同的名称

export interface People{

name: string
age: number
alive?: boolean
}

json comes like this 杰森是这样的

{
 {
 "name": "teste1"
 "age": 41
 "alive?": true
 }
}

load the json 加载json

@Injectable()
export class Peoples{
constructor(private http: Http){}

peoples(): Observable<People[]>{
    return this.http.get(`${DEEP_API}/people`)
    .map(response => response.json())
}
}

My problem is that the Person does not recognize the "?" 我的问题是,人不承认“?” in the "alive?" 在“活着?”

Any suggestion? 有什么建议吗?

If the property name contains special characters you need to put it in '' 如果属性名称包含特殊字符,则需要将其放入''

export interface People{
    name: string
    age: number
    'alive?': boolean
}

Note alive?: boolean is valid syntax, but it means the property named alive is optional, not that the property is named alive? 注意 alive?: boolean是有效的语法,但是它意味着名为alive的属性是可选的,而不是该属性被命名为alive?

To access the property you need to use person['alive?'] 要访问该属性,您需要使用person['alive?']

要添加@Titan所说的内容,您还应该知道,通过选择在属性名称中使用特殊字符,您将需要使用括号表示法 ["alive?"]来访问该属性值。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM