function use(x: any){
console.log(x);
}
type T = 'A' | 'B';
// consider all above fixed, do NOT change it in your answers (I am not asking about types in parameters of a function...)
// it only simulates what is in real code happening, it's just a minimal example
// works as I want, but requires temporary variable. clutters code quite a lot.
const a: T = 'C'; // <- crashes (compiler throws an error, desired behavior)
use(a);
// doesn't work - tsc happily compiles it and 'C' is assumed to be of type T
use(<T>'C');
use('C' as T);
我想要某种针对 I 类型的检查表达式。就像const
(如果右侧不是那种类型,它会崩溃),但没有临时变量 - 最好是内联,类似地,“类型断言”(类型转换)现在是如何工作的。
Edit1:这显然不是一个真正的代码,我的问题是严格关于在我写的“不起作用”的位置强制执行类型检查。不要改变功能,认为它是固定的。我知道如何在函数/vars/lets/consts/interfaces 中使用类型,但这不是这个问题的内容。
编辑2:另一个例子:
const input: any = 'SomeRealValueB'; // this comes from unsafe place, can't be safely typed without runtime checks which I really don't want to do
// ^ that can't be changed
type SomeRealType = 'SomeRealValueA' | 'SomeRealValueB';
// my current solution I am not happy with (unnecessary variable and line of code)
const someRealValueA: SomeRealType = 'SomeRealValueA';
if(input == someRealValueA) { console.log('y'); }
else { console.log('n'); }
// why I want it typed - consider that after refactoring 'SomeRealValueB' gets changed to 'SomeRealValueC', I want compiler to chceck that for me
正如字面所问,目前在 TypeScript 中没有内联编译时类型检查的语法。我想对这样的功能没有那么大的兴趣,因为你已经可以自己制作一个了:
function check<T>(x: T) { return x; }
以下几行将单独失败:
check<number>("five");
use(check<Ty>('C'));
但是,还必须注意的是,函数中缺乏适当的类型检查可能会隐藏一个单独的问题,因此,这里的函数是不可避免的。特别是,如果你的外部函数use
接受一个参数 as any
,而根据它自己的语义不应该,那么这只是一个糟糕的 TypeScript 声明,应该尽可能重新考虑和修复。否则,如果函数的声明无法更改,或者对参数类型的新限制只是您自己业务逻辑的一部分,那么您自己的应用程序应该将其包装到一个安全的、经过类型检查的函数中。
话虽如此,您目前有三个选择:(1)使用变量,就像您在问题中所做的那样;(2) 用预期的限制将函数包裹在一个新的声明中:
type Ty = 'A' | 'B';
const useTy: (x: Ty) => void = use;
useTy('C'); // Argument of type '"C"' is not assignable to parameter of type 'Ty'.
(3) 或者最后,由于函数本身是经过类型检查的,你可以像check
上面的函数一样创建一个恒等函数并使用它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句