无法使用打字稿向对象文字添加新属性 [英] Unable to add new properties to an object literal using typescript

查看:87
本文介绍了无法使用打字稿向对象文字添加新属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

There are questions on stackoverflow for the same but their accepted answers are not working for me as none of them is using an object literal. Without wasting your time. Here's my code.

contribute.component.ts ( contribute 只是我用 ng generate componenttribution 创建的我的组件的名称.)

contribute.component.ts (contribute is just a name of my component i created with 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 中是可变的.那为什么我会收到这个错误.

But my knowledge says that objects are mutable in ts. Then why I am getting this error.

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

error TS2339: Property 'email' does not exist on type '{}'. error TS2339: Property 'password' does not exist on type '{}'.

请告知我打字稿中的对象是否错误

Please tell if I am wrong about objects in typescript.

我还尝试将对象声明为:

I also tried declaring my object as:

makeNewPost= {
  email: string;
  password: string;
}

PS:这是一个Angular 8项目

PS: It is an Angular 8 project

推荐答案

TypeScript的主要意义在于它为变量提供了静态类型.当你做

Most of the point of TypeScript is that it provides static typing for variables. When you do

 makeNewPost={};

...由于尚未为 makeNewPost 指定类型,TypeScript会从 {} 推断出该类型,并使其成为没有属性的类型.当然,稍后,您将尝试添加属性,但是尽管在JavaScript中可以正常使用TypeScript的静态类型,但这是一个问题.

...since you haven't specified a type for makeNewPost, TypeScript infers it from {}, and makes it a type with no properties. Later, of course, you're trying to add properties, but while that's fine in JavaScript, with TypeScript's static typing, it's a problem.

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

The solution is to include the properties up front, and then just change their values:

 makeNewPost = {
    email: "",
    password: ""
 };

现在,TypeScript将使用 email password 属性(均为字符串)将类型推断为对象,以后可以分配给它们.

Now, TypeScript will infer the type as an object with email and password properties, both strings, and you can assign to them later.

您最初没有必须添加属性,尽管这可能是最干净的解决方案.您可以为 makeNewPost 定义类型,并使属性为可选(属性定义中的?):

You don't have to add the properties initially, though that's probably the cleanest solution. You could define a type for makeNewPost and make the properties optional (the ? in the property definition):

interface NewPost {
    email?: string;
    password?: string;
}

然后使用该类型:

makeNewPost: NewPost = {};

稍后,您将可以分配属性,因为允许它们存在.

Later, you'll be able to assign the properties because they're allowed to exist.

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

I wouldn't do that, though, because when you need to actually make a new post, those properties aren't optional.

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

A third approach would be to define a type without optional properties:

interface NewPost {
    email: string;
    password: string;
}

...并声明 makeNewPost Partial< NewPost> :

makeNewPost: Partial<NewPost> = {};

您将使 this._auth.registerNewt 接受 NewPost ,而不是 Partial< NewPost> ,但是使用 type断言在您填写完之后说(本质上)我现在已填写:"

You'd have this._auth.registerNewt accept NewPost, not Partial<NewPost>, but use a type assertion after you've filled it in to say (in essence) "I've filled it in now:"

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

this._auth.registerNewt(this.makeNewPost as NewPost)
// ...

这篇关于无法使用打字稿向对象文字添加新属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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