as
和<>
都完全忽略类型检查。我可以使用类似下面的函数来做同样的事情,同时检查类型,但我想知道是否有一个内置的机制来做同样的事情,以减少无用的公共函数的数量(因为它是大多数语言中的常见结构)?
const cast = <T>(x: T) => x
字符串
为了解释为什么需要这样做-我将一个对象字面量传递给泛型函数,我需要确保它被视为某种类型,同时还要确保我没有忘记任何属性。
as
和<>
都完全忽略类型检查。我可以使用类似下面的函数来做同样的事情,同时检查类型,但我想知道是否有一个内置的机制来做同样的事情,以减少无用的公共函数的数量(因为它是大多数语言中的常见结构)?
const cast = <T>(x: T) => x
字符串
为了解释为什么需要这样做-我将一个对象字面量传递给泛型函数,我需要确保它被视为某种类型,同时还要确保我没有忘记任何属性。
1条答案
按热度按时间6yt4nkrj1#
若要将变量强制转换为更宽的类型,请为其创建一个新变量:
字符串