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

Angular官方教程类的特殊用法疑问(Python转TypeScript入门)

Understanding Class Usage in Angular (Coming from Python)

Hey there! I totally get where you're coming from—switching from Python to TypeScript/Angular can feel like stepping into a slightly different world when it comes to classes and objects. Let's break down what's happening in the Angular tutorial to clear up that confusion.

First: TypeScript's Type System vs. Python's Class Model

Python uses a nominal type system, which means classes are defined by their name, and you must explicitly instantiate them with a constructor to create a usable object. TypeScript, on the other hand, relies on a structural type system—it cares more about the shape (properties and methods) of an object than its explicit class origin.

Here's how this plays out with the Hero class from the tutorial:

// The Hero class definition from the tutorial
export class Hero {
  id: number;
  name: string;
}

In Python, you'd create an instance like this (explicit instantiation is mandatory):

class Hero:
    def __init__(self, id: int, name: str):
        self.id = id
        self.name = name

hero = Hero(1, "Windstorm")

But in TypeScript, you can create an object that matches the shape of the Hero class without using new Hero():

const hero: Hero = { id: 1, name: "Windstorm" };

This works because TypeScript only checks that the object has the required id and name properties with the correct types—it doesn't require the object to be a direct instance created via the class constructor.

Why It Looks Like the Class Is Used Directly in Angular Templates

When you see the class referenced in the Angular template (like in the list display), you're not actually using the class itself—you're using instances (or shape-matching objects) stored in your component class.

Angular automatically instantiates your component class behind the scenes. For example, if your component has:

import { Component } from '@angular/core';
import { Hero } from './hero';

@Component({
  selector: 'app-heroes',
  templateUrl: './heroes.component.html'
})
export class HeroesComponent {
  heroes: Hero[] = [
    { id: 1, name: 'Windstorm' },
    { id: 2, name: 'Bombasto' }
  ];
}

Angular creates a live instance of HeroesComponent, and the template (heroes.component.html) accesses the heroes property from that instance. The Hero here acts only as a type checker to ensure each item in the array has the right structure.

When Would You Actually Use new Hero()?

If your Hero class included methods (not just properties), you would need to instantiate it with new to access those methods. For example:

export class Hero {
  id: number;
  name: string;

  greet(): string {
    return `Hello, I'm ${this.name}!`;
  }
}

// Now you need to instantiate to use the greet method
const hero = new Hero();
hero.id = 1;
hero.name = 'Windstorm';
console.log(hero.greet()); // Works!

But for simple data models (like the Hero in the tutorial), using object literals is more concise and common in Angular.

Wrap-Up

To recap:

  • TypeScript's structural typing lets you use objects that match a class's shape without explicit instantiation (perfect for data models).
  • Angular handles instantiating your component class, so the template uses properties from that live instance.
  • You only need new ClassName() when you need to use methods defined in the class.

It takes a little time to adjust from Python's strict instantiation rules, but once you get the hang of structural typing, it'll feel natural!

内容的提问来源于stack exchange,提问作者Chris Kavanagh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:27:48