无法使用打字稿向对象文字添加新属性

Tan*_*eel 5 javascript object typescript angular

stackoverflow 上也有同样的问题,但他们接受的答案对我不起作用,因为他们都没有使用对象文字。无需浪费您的时间。这是我的代码。

tribute.component.tscontribute只是我用它创建的组件的名称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)
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

但据我所知,对象在ts. 那为什么我会收到这个错误。

错误 TS2339:类型“{}”上不存在属性“电子邮件”。错误 TS2339:类型“{}”上不存在属性“密码”。

请告诉我我对打字稿中的对象是否有误。

我还尝试将我的对象声明为:

makeNewPost= {
  email: string;
  password: string;
}
Run Code Online (Sandbox Code Playgroud)

PS:这是一个Angular 8项目

T.J*_*der 7

TypeScript 的主要优点是它为变量提供静态类型。当你这样做时

 makeNewPost={};
Run Code Online (Sandbox Code Playgroud)

...由于您尚未指定 的类型makeNewPost,TypeScript 会从 推断出它{},并使其成为没有属性的类型。当然,稍后您会尝试添加属性,但这在 JavaScript 中没问题,但对于 TypeScript 的静态类型来说,这是一个问题。

解决方案是预先包含属性,然后只需更改它们的值:

 makeNewPost = {
    email: "",
    password: ""
 };
Run Code Online (Sandbox Code Playgroud)

现在,TypeScript 会将类型推断为具有emailpassword属性(均为字符串)的对象,您可以稍后分配给它们。


您不必最初添加属性,尽管这可能是最干净的解决方案。您可以定义类型makeNewPost并使属性可选?在属性定义中):

interface NewPost {
    email?: string;
    password?: string;
}
Run Code Online (Sandbox Code Playgroud)

然后使用该类型:

makeNewPost: NewPost = {};
Run Code Online (Sandbox Code Playgroud)

稍后,您将能够分配这些属性,因为它们被允许存在。

不过,我不会这样做,因为当您实际需要发布新帖子时,这些属性不是可选的。

第三种方法是定义一个没有可选属性的类型:

interface NewPost {
    email: string;
    password: string;
}
Run Code Online (Sandbox Code Playgroud)

...并声明makeNewPostPartial<NewPost>

makeNewPost: Partial<NewPost> = {};
Run Code Online (Sandbox Code Playgroud)

您可以this._auth.registerNewt接受NewPost,而不是Partial<NewPost>,但在填写后使用类型断言来表示(实质上)“我现在已经填写了:”

this.makeNewPost.email = email;
this.makeNewPost.password = password;

this._auth.registerNewt(this.makeNewPost as NewPost)
// ...
Run Code Online (Sandbox Code Playgroud)