[英]Unable to add new properties to an object literal using typescript
對於stackoverflow也有同樣的問題,但是他們接受的答案對我不起作用,因為它們都沒有使用對象文字。 不浪費您的時間。 這是我的代碼。
commit.component.ts ( contribute
只是我用ng generate component contribute
創建的我的組件的名稱)。
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { AuthService } from '../auth.service';
@Component({
selector: 'app-contribute',
templateUrl: './contribute.component.html',
styleUrls: ['./contribute.component.css']
})
export class ContributeComponent implements OnInit {
makeNewPost={}; //THI IS MY EMPTY OBJECT TO WHICH I WANT TO ADD PROPERTIES LATER IN THIS CODE
constructor(private _auth: AuthService) { }
ngOnInit() {
//SOME CODE
}
//THIS FUNCTION WILL BE CALLED ON CLICK EVENT FROM `contribute.component.html`
onSubmit() {
var email = (<HTMLInputElement>document.getElementById("email")).value;
var password = (<HTMLInputElement>document.getElementById("password")).value;
console.log(email); //SEEMS GOOD ON CONSOLE
console.log(password); //SEEMS GOOD ON CONSOLE
//THESE TWO PROPERTIES I WANT TO ADD
this.makeNewPost.email=email;
this.makeNewPost.password=password;
this._auth.registerNewt(this.makeNewPost)
.subscribe (
res => console.log(res),
err => console.log(err)
);
}
}
但據我所知,對象在ts
是可變的。 那為什么我得到這個錯誤。
錯誤TS2339:類型“ {}”上不存在屬性“電子郵件”。 錯誤TS2339:類型“ {}”上不存在屬性“密碼”。
請告訴我,如果我錯了有關打字稿對象。
我還嘗試將我的對象聲明為:
makeNewPost= {
email: string;
password: string;
}
PS:這是一個Angular 8項目
TypeScript的主要意義在於它為變量提供了靜態類型 。 當你做
makeNewPost={};
...由於您尚未為makeNewPost
指定類型, makeNewPost
TypeScript從{}
推斷出它的類型,並使它成為沒有屬性的類型。 當然,稍后,您嘗試添加屬性,但是在JavaScript中可以正常使用TypeScript的靜態類型,但這是一個問題。
解決方案是先包含屬性,然后更改它們的值:
makeNewPost = {
email: "",
password: ""
};
現在,TypeScript會將類型推斷為具有email
和password
屬性(兩個字符串)的對象,您以后可以分配給它們。
您不必一開始就添加屬性,盡管這可能是最干凈的解決方案。 您可以為makeNewPost
定義類型,並使屬性為可選 (屬性定義中的?
):
interface NewPost {
email?: string;
password?: string;
}
然后使用該類型:
makeNewPost: NewPost = {};
稍后,您將能夠分配屬性,因為它們被允許存在。
不過,我不會這樣做,因為當您實際需要撰寫新文章時,這些屬性不是可選的。
第三種方法是定義沒有可選屬性的類型:
interface NewPost {
email: string;
password: string;
}
...並聲明makeNewPost
為Partial<NewPost>
:
makeNewPost: Partial<NewPost> = {};
您將具有this._auth.registerNewt
接受NewPost
,而不是Partial<NewPost>
,但是在填寫它之后使用類型斷言來說(本質上)“我現在已經將其填寫:”
this.makeNewPost.email = email;
this.makeNewPost.password = password;
this._auth.registerNewt(this.makeNewPost as NewPost)
// ...
您正在使用TypeScript。 您可以為“發布”創建類型:
export interface Post{
email : String
password : String
}
然后將makeNewPost
聲明為Post
類型,並立即使用您的值將其初始化:
let makeNewPost: Post = {
email : email,
password : password
}
如果您事先不知道對象的屬性,則可以進行如下自定義類型:
type NewObject = {[key: string]: any};
let newObject: NewObject = {};
newObject.property = 'value';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.