简体   繁体   中英

Defining typescript generics with type safety

Can you define generics with safe types, as you can with c#?

Eg

public bool Foo<T>() where T : struct { /* */ }

Typescript now has generics, but can I perform a similar action?

Thanks.

Ok it seems you can do this:

Foo<T extends IBar>() { /* */ }

And that seems to make all calls require the T to implement IBar .

如果您不想创建额外的类/接口,例如,您可以执行以下操作:

Foo<T extends{ id: string | number }>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM