To type arrays, we use generics.
Suppose you want an array to only contain numbers.
This is how you type it:
const nums: Array<number> = [1, 2, 3]
You can now add numbers to the array, but if you add a string for example you’ll have an error:
We use generics often with useState
in React:
type GitHubData = {
avatar_url: string
name: string
created_at: string
bio: string
}
function App() {
const [data, setData] = useState<GitHubData>()
}
Lessons in this unit:
0: | Introduction |
1: | Your first TypeScript program |
2: | Types |
3: | Typing functions |
4: | The editor helps you with type errors |
5: | Running TypeScript code |
6: | Valid types |
7: | Type aliases and interfaces |
8: | Union types |
9: | ▶︎ Typing arrays with generics |
10: | The DX of editing TypeScript |
11: | There's more... |
12: | tsconfig.json COMING SOON |
13: | Installing types COMING SOON |
Are you intimidated by Git? Can’t figure out
merge vs rebase? Are you afraid of screwing up
something any time you have to do something in
Git? Do you rely on ChatGPT or random people’s
answer on StackOverflow to fix your problems?
Your coworkers are tired of explaining Git to
you all the time? Git is something we all need
to use, but few of us really master it. I
created this course to improve your Git (and
GitHub) knowledge at a radical level. Launching
May 21, 2024. Join the waiting list!