Posts > TS Basic: Type VS Interface

TS Basic: Type VS Interface

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.

Type

  • can be assigned as string, number, boolean, or object
  • the syntax for type level is type User = {}
👌consider using type for your React Component Props and State, for consistency and because it is more constrained. - react-typescript-cheetsheet

Interface

  • only assigned to an object
  • the syntax for interface level is 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

Extending Type and Interface

  • you can only extends object-like type to a interface
type User = string

interface extends User {} // this is wrong! ❌

type User = {}

interface extends Users {} // this is correct! ✅
  • extends multiple interface
interface 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,
    }
}
  • type level can also be extended by using the intersection syntax &
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 use type or interface as a rule of thumb is to use them consistently within your code. Whether you use only type in your project or only interface.Using them both will have no issue except for your code consistency.

Tags 🏷