You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TypeScript中为user_roles变量声明类型而非使用any

用TypeScript为FormGroup声明类型替代any的方案

首先定义一个接口来描述表单的结构,对应每个表单控件的值类型:

interface UserRoleForm {
  name: string;
  email: string;
  role: string;
  password: string;
}

接着给user_roles指定FormGroup<UserRoleForm>类型,替换掉any:

import { FormGroup, FormControl } from '@angular/forms';

interface UserRoleForm {
  name: string;
  email: string;
  role: string;
  password: string;
}

user_roles: FormGroup<UserRoleForm> = new FormGroup({
  name: new FormControl(''),
  email: new FormControl(''),
  role: new FormControl(''),
  password: new FormControl(''),
});

额外说明

如果表单控件可能返回null(比如清空输入时),可以把接口类型调整为string | null,同时给FormControl指定泛型:

interface UserRoleForm {
  name: string | null;
  email: string | null;
  role: string | null;
  password: string | null;
}

user_roles: FormGroup<UserRoleForm> = new FormGroup({
  name: new FormControl<string | null>(''),
  email: new FormControl<string | null>(''),
  role: new FormControl<string | null>(''),
  password: new FormControl<string | null>(''),
});

这样做能获得TypeScript的类型校验和智能提示,避免any带来的类型不安全问题。

内容的提问来源于stack exchange,提问作者Sen Kanna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 05:45:36