Posts > TS Basic: Type VS Interface
September 19, 2024
When do we use type
vs interface
? Which should we use? When do we use type
and interface
? And why I’m starting my post like this? I read too many self-help books I guess.
string
, number
, boolean
, or object
type User = {}
👌consider using type for your React Component Props and State, for consistency and because it is more constrained. - react-typescript-cheetsheet
object
interface User {}
(interface doesn’t have a =
syntax👌Always use interface for public API’s definition when authoring a library or 3rd party ambient type definitions, as this allows a consumer to extend them via declaration merging if some definitions are missing - react-typescript-cheetsheet
extends
object-like type to a interfacetype User = string
interface extends User {} // this is wrong! ❌
type User = {}
interface extends Users {} // this is correct! ✅
extends
multiple interfaceinterface User {
id: string,
}
interface Details {
address: string,
}
interface UserDetail extends User, Details {
name: string,
age: number,
}
const UserDetail = () : UserDetail => {
return {
id: 'foo',
address: 'anywhere',
name: 'Owa',
age: 21,
}
}
&
interface User {
id: string,
name: string,
age: string,
}
interface Post {
id: string,
title: string,
body: string,
}
const getUserAndPosts = () : User & { posts: Post[] } => {
return {
id: '1',
name: 'Owa',
age: '25',
posts: [
{
id: '1',
title: 'Post 1',
body: 'The quick brown fox jumps over the lazy dog'
}
]
}
}
notice the type annotation User & { posts: Post[ ] } this is the syntax for intersecting two interface / type
type User = {
id: string,
name: string,
age: string,
}
interface Post {
id: string,
title: string,
body: string,
}
type Address = string
type UserAndPosts = User & { posts: Post[]}
// you can also add more intersections
// type UserAndPosts = User & { posts: Post[]} & { address: Address }
const getUserAndPosts = () : UserAndPosts => {
return {
id: '1',
name: 'Owa',
age: '25',
posts: [
{
id: 'p',
title: 'p',
body: 'b'
}
],
//address: 'foo'
}
}
you can also do something like this, making it more readable
👌In the end, it depends if you want to usetype
orinterface
as a rule of thumb is to use them consistently within your code. Whether you use onlytype
in your project or onlyinterface
.Using them both will have no issue except for your code consistency.