【问题标题】:Force angular to respect type of interface in a json强制角度尊重 json 中的接口类型
【发布时间】:2020-06-11 00:38:33
【问题描述】:

举个例子:

model.ts

export interface Item{
  name: string;
  age: string
}

component.ts

form: FormGroup

constructor(private fb: FormBuilder){}

onInit(){
  this.form = fb.group({
    name: [''],
    age: ['']
})
}
exampleFn(){
  const signature: Item = Object.assign({},this.form.value);

  console.log(typeof(signature.age)); // <=== HERE
  // output number

}

html

<form [formGroup]="form">
  <input formControlName="name" type="text"/>
  <input formControlName="age" type="number"/>
</form>

为什么值不是字符串?在模型中是用字符串定义的,虽然输入类型是数字,因为我想友好地显示它,但我需要一个字符串,而且我不想单独转换(在一个模型中输入了一堆 itens 的场景中思考) .

谢谢

堆栈闪电战示例

https://stackblitz.com/edit/angular-ivy-z1sygf

【问题讨论】:

  • 是的,因为输入类型用数字填充,但我需要将其作为字符串发送到 json 对象中。但是,无需单独解析,因为这是一个具有 2 个属性的简单示例,在实际情况下,我有 100 多个属性并且可以更多。
  • 但我不知道如何,正在发送号码
  • 对不起,我误解了你的问题。不,您不能仅通过使用接口使其输出字符串。您需要手动转换它。
  • typescript 上的类型只是编码过程中的一个助手,但它们不会保留在构建的代码上。
  • 谢谢 Elias,我会遭受手动解析????

标签: angular typescript validation


【解决方案1】:

另一个答案是 100% 正确,您想要做的事情应该在其他地方的映射函数中完成,但您仍然可以使用仅允许数字的 directive 来完成。

使用链接中的指令,html 将如下所示:

<form *ngIf="form" [formGroup]="form">
  <input formControlName="name" type="text"/>
  <input formControlName="age" numbersOnly/>
</form>

我不是写指令的人,我仍然认为你应该找到另一种方法。

【讨论】:

    【解决方案2】:

    该值不是字符串,因为您的输入设置为type="number"

    Typescript 只是 Javascript 的超集,您的界面并不存在。将所有代码转译为 JS 后,将 form.value(根据 [docs][1] 为 any 类型)分配给强类型变量将不会尝试将每个属性值转换或强制转换为特定类型.

    使用以下打字稿:

    //declare strongly typed interface
    interface Item {
      name: string;
      age: string
    };
    
    //create a value of type any, which is essentially what "formGroup.value" is
    const myFormValue: any = {
        name: '',
        age: '' //it's a string!
    };
    
    //set the value to a number, as what happens when someone interacts with your number input
    myFormValue.age = 42;
    
    //Assign and cast "myFormValue" as an "Item"
    //This will not implicitly try to convert values for you
    const formValueAsItem: Item = myFormValue;
    
    console.log(formValueAsItem);
    

    现在,看看它归结为 JS 后的样子:

    //create a value of type any, which is essentially what "formGroup.value" is
    const myFormValue = {
        name: '',
        age: '' //it's a string!
    };
    
    //set the value to a number, as what happens when someone interacts with your number input
    myFormValue.age = 42;
    
    //There's no type here, we're simply creating a new variable and assigning it a value.
    const formValueAsItem = myFormValue;
    
    console.log(formValueAsItem);
    

    【讨论】:

    • 好吧,我相信模型会完成这项工作,但不是。谢谢你的解释,我明白了。
    猜你喜欢
    • 2021-06-24
    • 2017-01-14
    • 1970-01-01
    • 1970-01-01
    • 2016-12-09
    • 1970-01-01
    • 2019-06-15
    • 2017-11-05
    • 1970-01-01
    相关资源
    最近更新 更多