最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

typescript - How to extractinfer the raw value type from a Signal, Input, or Output of Angular? - Stack Overflow

programmeradmin1浏览0评论

If I have something like this:

import { Component, output } from '@angular/core';

@Component({...})
export class MyComponent {
  success= output<{message: string, response: SomeModelNotExported}>;
}

I am currently doing a Type extraction via indexed access and conditional inference

 onSuccess(event: MyComponent['success'] extends OutputEmitterRef<infer T> ? T : never) { // type is inferred here as {message: string, response: SomeModelNotExported} 
    ...
 }

It just looks too bloody. Is there a more friendlier approach to this? Am I missing some already available types exported by Angular?

If I have something like this:

import { Component, output } from '@angular/core';

@Component({...})
export class MyComponent {
  success= output<{message: string, response: SomeModelNotExported}>;
}

I am currently doing a Type extraction via indexed access and conditional inference

 onSuccess(event: MyComponent['success'] extends OutputEmitterRef<infer T> ? T : never) { // type is inferred here as {message: string, response: SomeModelNotExported} 
    ...
 }

It just looks too bloody. Is there a more friendlier approach to this? Am I missing some already available types exported by Angular?

Share Improve this question edited Feb 28 at 3:40 Alex Pappas asked Feb 20 at 5:49 Alex PappasAlex Pappas 2,6783 gold badges31 silver badges61 bronze badges 1
  • I'm curious how angular infers the raw value type from the template when you are using the $event in the output binding as well. – Alex Pappas Commented Feb 20 at 5:51
Add a comment  | 

1 Answer 1

Reset to default 1

You can explicitely define a type, which accepts the generic as an input, then use this generic type across your component.

export type OutputType<T> = {
  message: string;
  response: T;
};

@Component({ selector: 'my-component', template: '' })
export class MyComponent<TResponse> {
  success = output<OutputType<TResponse>>();

  onSuccess(event: OutputType<TResponse>) {
    console.log(event.message);
  }
}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论