如何定义从具有 InputSignal 属性的抽象类继承的 Angular 组件记录?

问题描述 投票:0回答:1

我尝试像这样定义一个记录:

// imports...

export abstract class AbstractComponent<T extends string> {
  abstract prop: InputSignal<T>;
}

export class TestComponent extends AbstractComponent<'test'> {
  prop: InputSignal<'test'> = input('test');
}

@Component({ standalone: true, template: `` })
export class App {
  component: Record<string, typeof AbstractComponent<string>> = {
    'test-1': TestComponent,
  };
}

我收到此错误:

Type 'typeof TestComponent' is not assignable to type 'typeof AbstractComponent<string>'.
  Construct signature return types 'TestComponent' and 'AbstractComponent<string>' are incompatible.
    The types of 'prop[SIGNAL].transformFn' are incompatible between these types.
      Type '((value: "test") => "test") | undefined' is not assignable to type '((value: string) => string) | undefined'.
        Type '(value: "test") => "test"' is not assignable to type '(value: string) => string'.
          Types of parameters 'value' and 'value' are incompatible.
            Type 'string' is not assignable to type '"test"'.(2322)

如何修复错误?

StackBlitz 演示

angular typescript
1个回答
0
投票

当我们应该传递类型为

'test'
时,为什么你要传递
string
,这似乎可以解决你的问题!

参数

InputSignal<T>
,其中 T 是类型,最好将其定义为
string

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

export abstract class AbstractComponent<T extends string> {
  abstract prop: InputSignal<T>;
}

export class TestComponent extends AbstractComponent<string> {
  prop: InputSignal<string> = input('test');
}

@Component({ standalone: true, template: ``, selector: 'app-root' })
export class App {
  component: Record<string, typeof AbstractComponent<string>> = {
    'test-1': TestComponent,
  };
}

bootstrapApplication(App);

Stackblitz 演示

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