有没有办法向模板输入变量添加类型断言/注释? [英] Is there a way to add a type assertion / annotation to a template input variable?
问题描述
我有一个看起来像这样的模板(我正在使用一些组件,它使用它作为重复项的基础,它是 <p-pickList>
,但问题不是具体到那个组件,只是一个例子)
I have a template that looks like this (I'm using some component that uses this as the basis for a repeated item, it's the <p-pickList>
, but the question is not specific about that component, just as an example)
对于背景,假设我有一个 Foo
类型并且我的组件有一个 foos: Foo[]
,我将它提供给 <
组件,它为它做内部 [source]
属性下的 p-pickList>*ngFor
,我所要做的就是提供一个模板>
For background, let's say I have a type Foo
and my component has a foos: Foo[]
, I'm feeding it to the <p-pickList>
component under the [source]
attribute and its doing the internal *ngFor
for it, all I have to do is provide a template
<ng-template let-foo pTemplate="item">
...
{{ foo.anythingGoesHereWithNoWarningAndNoAutocomplete }}
然而,foo
上的类型信息似乎丢失了.
However, the type information on foo
seems to be lost.
我是类型安全的忠实拥护者,我喜欢 Intellij(或任何其他编辑器)可以向我显示警告,如果在模板中我执行了诸如指定 foo
的无效属性之类的操作
I'm a big fan of type safety and I like that Intellij (or any other editor) can show me a warning if inside the template I do something like specifying an invalid attribute of foo
如果我有一个常规的 *ngFor
,它会推断 foo
If I had a regular *ngFor
, it would infer the type of foo
<div *ngFor="let foo of foos">
{{ foo.autoCompleteWorksInMostIDEsAsWellAsWarningIfInvalidProp }}
Questions:
问题:
是否有任何语法可以让我暗示
let-foo
的类型?(希望大多数 IDE 都能识别).
If I don't want to rely on IDE's, is there a way to have the ng compiler type check foo
(declared by let-foo)?
如果我不想依赖 IDE,有没有办法让 ng 编译器类型检查 foo
(由 let-foo 声明)?
tl;dr is there a syntax that let me type annotate the template input variable? e.g. something like this made up syntax?
tl;dr 是否有一种语法可以让我输入注释模板输入变量?例如这样的东西组成了语法?
let-foo="$implicit as Foo"
or let-foo-type="Foo"
?
let-foo=$implicit as Foo"
还是 let-foo-type=Foo"
?
一个愚蠢的想法是在我的组件中有一个标识函数,例如
identity(foo: Foo): Foo {
return foo;
}
But doing
但是做
Is not a big improvement over
不是很大的改进
推荐答案
VSCode 应该具有开箱即用的功能,刚刚在 stackblitz 中测试:
这篇关于有没有办法向模板输入变量添加类型断言/注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!