我在使用typescript的react应用程序中工作。其中一个函数在其中一个变量中接收泛型类型。
如何检查变量的T类型?这个是可能的吗?
MyFunction<T>(newValues: Array<T>) {
if (typeof T === "string") {
// do some stuff
}
}
我试图在TypeScript中实例化一个泛型类。
在C#,我会这样做的
class MyPacket<T> {...}
var t = typeof(...);
var genericContainer = typeof(MyPacket<>).MakeGenericType(new[]{ t });
var instance = Activator.CreateInstance(genericContainer);
我的用例是,我正在接收来自网络的消息。我还有一个EventEmitter,它期望被调用的类型是正确的。
(msg: Message): void =&g
我开始学习脚本语言,特别是JavaScript。这很好,当我和Angular2一起学习TypeScript时,我开始感到困惑。
我意识到TypeScript可以定义内置类型,如字符串、数字和对象,而TypeScript将在编译时生成JavaScript。
这里开始了我的困惑,TypeScript是如何在JavaScript上定义泛型类型的,因为JavaScript是基于原型的语言,它不能定义类型。
例如,如何将下列代码编译到JavaScript中。
interface Person {
name : string,
age : number
}
有人能解释一下吗?脚本很有趣,但有时
我使用的是angularjs (1.5.8)框架和最新的typescript (2.8.0)文件。更新到最新的typescript版本后,以下代码未编译。
Angular接口实现:
interface IPromise<T> {
/**
* Regardless of when the promise was or will be resolved or rejected, then calls one of the success or error callbacks asynchronously as soon as the result is availab
如果一个函数的一个参数是两个类型的并集,我如何才能正确地推断返回类型? 我已经尝试了以下条件类型,但它不起作用(参见typescript错误的内联注释): TypeScript Playground type Status = 'statusType'
type GoalActivity = 'goalActivityType'
type Argument = { type: 'status'; status: Status | null } | { type: 'goalActivity'; goalActivity: Go
Flow有一个方便的,它可以获得调用类型F的函数的返回类型,第一个参数(可选)作为类型T,第二个参数等等。所以我们可以这样做:
type First = <T>(Array<T>) => T | void;
type ShouldBeOptionalString = $Call<First, Array<string>>; // ShouldBeOptionalString is string | void
TypeScript能实现同等的功能吗?我知道TypeScript提供的,但它不能根据参数类型计算返回类型:
type First =
我有一些打字代码:
const wrapField = <T extends { value: string }>(fieldValue: string): T => ({
value: fieldValue,
});
Typescript给我一个错误:
'{ value: string; }' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint