Typescript 如何获取类或接口的可选属性的类型

问题描述 投票:0回答:1
class Load  {
    ID: number;
    Action?: string;
    public getType(name: string) {
    return typeof this[name];
    }

    constructor() { }
}

    let _load =new Load()
    _load.ID = 5

    console.log(_load.getType("ID")) // It logs number
    console.log(_load.getType("Action")) //It logs undefined. But it should be string for me

我想获取类中所有属性的类型,无论它是否有值。但如果尚未设置 可选 属性,getType 始终返回 undefined

我可以使用接口而不是类,没关系。我该如何解决?

提前致谢!

angular typescript class
1个回答
0
投票

因为您将值设置为

ID
,所以您得到
number
类型,否则也将是未定义的。相反,只需在类顶部或构造函数上初始化属性,这将始终为您提供所需的类型。

class Load {
  ID!: number;
  Action?: string;
  public getType(name: string) {
    return typeof (this as any)[name];
  }

  constructor(ID: number, Action = '') {
    this.ID = ID;
    this.Action = Action;
  }
}

完整代码:

import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';

class Load {
  ID!: number;
  Action?: string;
  public getType(name: string) {
    return typeof (this as any)[name];
  }

  constructor(ID: number, Action = '') {
    this.ID = ID;
    this.Action = Action;
  }
}

@Component({
  selector: 'app-root',
  standalone: true,
  template: `
    <h1>Hello from {{ name }}!</h1>
    <a target="_blank" href="https://angular.dev/overview">
      Learn more about Angular
    </a>
  `,
})
export class App {
  name = 'Angular';

  ngOnInit() {
    let _load = new Load(1);

    console.log(_load.getType('ID')); // It logs number
    console.log(_load.getType('Action')); //It logs undefined. But it should be string for me
  }
}

bootstrapApplication(App);

Stackblitz 演示

© www.soinside.com 2019 - 2024. All rights reserved.