[TypeScript] The Basics of Generics in TypeScript
It can be painful to write the same function repeatedly with different types. Typescript generics allow us to write 1 function and maintain whatever type(s) our function is given. This lesson covers syntax and a basic use case for Typescript generics.
We have a reusable function that pushes something into a collection, and then console logs the collection. We have two objects, and two arrays. We can just call the function with anything an array,
function pushSomethingIntoCollection(something, collection) { collection.push(something); console.log(collection); } let jeanGrey = { name: "Jean Grey" }; let wolverine = { name: "Wolverine" }; let superHeroes = [jeanGrey]; let powers = ["telekinesis", "esp"]; pushSomethingIntoCollection("cool", superHeroes); pushSomethingIntoCollection("adamantium claws", []);
but we're human and we make errors. What we want is to make sure we're pushing the right something, into the right array.
We can use a generic to tell the compiler, we're going to be using a specific type, but we're not going to tell you what that type is until the function is called. This is what a generic looks like. It doesn't matter what's between the angle brackets, as long as it makes sense to you.
function pushSomethingIntoCollection<T>(something: T, collection: T[])
Now if we do:
pushSomethingIntoCollection("meh", superHeroes);
IDE will show us error, because 'something: T' is string type, then collection should be array to string type.
But 'superHeros' is array of object type.
interface SuperHero {name: string;} pushSomethingIntoCollection<SuperHero>("meh", superHeroes); //Error pushSomethingIntoCollection<string>("adamantium claws", []); //OK
We can provide interface to tell IDE what generice type should be. So IDE can help to catch error.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具