Types vs Interfaces in TypeScript

We have two options for defining types in TypeScript: types and interfaces. In this tutorial, we will discuss the key differences and similarities between types and interfaces in TypeScript and explore when it is appropriate to use each one.

The Difference between TypeScript Interfaces and Types

We have two options for defining types in TypeScript: types and interfaces. One of the most frequently asked questions about TypeScript is whether we should use interfaces or types.

The answer to this question, like many programming questions, is that it depends. There are cases where one has a clear advantage over the other, but in many cases they are interchangeable.

In this article, I will discuss the key differences and similarities between types and interfaces and explore when it is appropriate to use each one.

Table of contents:

  • Types and type aliases
  • Interfaces in TypeScript
  • Differences between types and interfaces
    • Declaration merging
    • Extends vs. intersection
    • Handling conflicts when extending
    • Implementing classes using interfaces or type aliases
    • Working with tuple types
  • Advanced type features
  • When to use types vs. interfaces

Let’s start with the basics of types and interfaces.


Types and type aliases

type is a keyword in TypeScript that we can use to define the shape of data. The basic types in TypeScript include:

  • String
  • Boolean
  • Number
  • Array
  • Tuple
  • Enum
  • Advanced types

Each of these comes with its unique features and purposes, allowing developers to choose the appropriate one for their particular use case.

Type aliases in TypeScript mean “a name for any type.” They provide a way of creating new names for existing types. Type aliases don’t define new types; instead, they simply provide an alternative name for an existing type.

Type aliases can be created using the type keyword, and can refer to any valid TypeScript type, including primitive types.

type MyNumber = number;
type User = {
  id: number;
  name: string;
  email: string;
}

In the above example, we create two type aliases: MyNumber and User. We can use MyNumber as shorthand for a number type, and use User type aliases to represent the type definition of a user.

When we say “types versus interfaces,” what we are actually referring to is “type aliases versus interfaces”. For example, you can create the following aliases:

type ErrorCode = string | number;
type Answer = string | number;

The two type aliases above represent alternative names for the same union type: string | number. While the underlying type is the same, the different names express different intents, which makes the code more readable.

Interfaces in TypeScript

In TypeScript, an interface defines a contract that an object must adhere to. Below is an example:

interface Client { 
    name: string; 
    address: string;
}

We can express the same Client contract definition using type annotations:

type Client = {
    name: string;
    address: string;
};

Differences between types and interfaces

For the above case, you can use either type or interface. But there are some scenarios in which using type instead of interface makes a difference.

Declaration merging

Declaration merging is a feature that is exclusive to interfaces. With declaration merging, we can define an interface multiple times and the TypeScript compiler will automatically merge these definitions into a single interface definition.

In the following example, the two Client interface definitions are merged into one by the TypeScript compiler, and we have two properties when using the Client interface:

interface Client { 
    name: string; 
}

interface Client {
    age: number;
}

const harry: Client = {
    name: 'Harry',
    age: 41
}

Type aliases can’t be merged in the same way. If you try to define the Client type more than once, as in the above example, an error will be thrown:

Defining a type more than once will result in an error

Defining a type more than once will result in an error

When used in the right places, declaration merging can be very useful. One common use case for declaration merging is to extend a third-party library’s type definition in order to fit the needs of a particular project.

If you find yourself needing to merge declarations, interfaces are the way to go.

Extends vs. intersection

An interface can extend one or multiple interfaces. By using the extends keyword, a new interface can inherit all the properties and methods of an existing interface, while also adding new properties.

For example, we can create a VIPClient interface by extending the Client interface:

interface VIPClient extends Client {
    benefits: string[]
}

To achieve a similar result for types, we need to use an intersection operator:

type VIPClient = Client & {benefits: string[]}; // Client is a type

You can also extend an interface from a type alias with statically known members:

type Client = {
    name: string;
};

interface VIPClient extends Client {
    benefits: string[]
}

The exception is union types. Union types allow us to describe values that can be one of several types and create unions of various primitive types, literal types, or complex types.

There is no equivalent to a union type in an interface. If you try to extend an interface from a union type, you’ll receive the following error:

type Jobs = 'salary worker' | 'retired';

interface MoreJobs extends Jobs {
  description: string;
}

The error thrown when a union type is not statically known

This error occurs because the union type is not statically known. The interface definition needs to be statically known at compile time.

Type aliases can extend interfaces using the intersection, as below:

interface Client {
    name: string;
}
Type VIPClient = Client & { benefits: string[]};

In a nutshell, both interfaces and type aliases can be extended. An interface can extend a statically known type alias, while a type alias can extend an interface using an intersection operator.

Handling conflicts when extending

Another difference between types and interfaces is how conflicts are handled when you try to extend from one with the same property name.

When extending interfaces, the same property key isn’t allowed, as in the example below:

interface Person {
  getPermission: () => string;
}

interface Staff extends Person {
   getPermission: () => string[];
}

An error is thrown because a conflict is detected.

When a conflict is detected, an error is thrown

When a conflict is detected, an error is thrown

Type aliases handle conflicts differently. In the case of a type alias extending another type with the same property key, it will automatically merge all properties instead of throwing errors.

In the following example, the intersection operator merges the method signature of the two getPermission declarations, and a typeof operator is used to narrow down the union type parameter, so we can get the return value in a type-safe way:

type Person = {
  getPermission: (id: string) => string;
};

type Staff = Person & {
   getPermission: (id: string[]) => string[];
};

const AdminStaff: Staff = {
  getPermission: (id: string | string[]) =>{
    return (typeof id === 'string'?  'admin' : ['admin']) as string[] & string;
  }
}

It is important to note that the type intersection of two properties may produce unexpected results. In the example below, the name property for the extended type Staff becomes never, since it can’t be both string and number at the same time:

type Person = {
    name: string
};

type Staff = person & {
    name: number
};
// error: Type 'string' is not assignable to type 'never'.(2322)
const Harry: Staff = { name: 'Harry' };

In summary, interfaces will detect property or method name conflicts at compile time and generate an error, whereas type intersections will merge the properties or methods without throwing errors. Therefore, if we need to overload functions, type aliases should be used.

Implementing classes using interfaces or type aliases

In TypeScript, we can implement a class using either an interface or a type alias:

interface Person {
  name: string;
  greet(): void;
}

class Student implements Person {
  name: string;
  greet() {
    console.log('hello');
  }
}

type Pet = {
  name: string;
  run(): void;
};

class Cat implements Pet {
  name: string;
  run() {
    console.log('run');
  }
}

As shown above, both interfaces and type aliases can be used to implement a class similarly; the only difference is that we can’t implement a union type.

type primaryKey = { key: number; } | { key: string; };

// can not implement a union type
class RealKey implements primaryKey {
  key = 1
}

An error is thrown because the class represents a specific data shape

In the above example, the TypeScript compiler throws an error because a class represents a specific data shape, but a union type can be one of several data types.

Working with Tuple types

In TypeScript, Tuple type allows us to express an array with a fixed number of elements, where each element has its own data type. It can be useful when you need to work with arrays of data with a fixed structure:

type TeamMember = [name: string, role: string, age: number];

Interfaces don’t have direct support for tuple types. Although we can create some workarounds like in the example below, it is not as concise or readable as using the tuple type:

interface ITeamMember extends Array<string | number> 
{
 0: string; 1: string; 2: number 
}

const peter: ITeamMember = ['Harry', 'Dev', 24];
const Tom: ITeamMember = ['Tom', 30, 'Manager']; //Error: Type 'number' is not assignable to type 'string'.

Advanced type features

TypeScript provides a wide range of advanced type features that can’t be found in interfaces. Some of the unique features in TypeScript include:

  • Type inferences: Can infer the type of variables and functions based on their usage. This reduces the amount of code and improves readability
  • Conditional types: Allow us to create complex type expressions with conditional behaviors that depend on other types
  • Type guards: Used to write sophisticated control flow based on the type of a variable
  • Mapped types: Transforms an existing object type into a new type
  • Utility types: A set of out-of-the-box utilities that help to manipulate types

TypeScript’s typing system is constantly evolving with every new release, making it a complex and powerful toolbox. The impressive typing system is one of the main reasons why many developers prefer to use TypeScript.

When to use types vs. interfaces

Type aliases and interfaces are very similar, but have some subtle differences, as shown in the previous section.

While almost all interface features are available in types or have equivalents, there is one exception: declaration merging. In general, interfaces should be used in scenarios where declaration merging is necessary, such as extending an existing library or authoring a new library. Additionally, if you prefer the object-oriented inheritance style, using the extends keyword with an interface is often more readable than using the intersection with type aliases.

However, many of the features in types are difficult or impossible to achieve with interfaces. For example, TypeScript provides a rich set of features like conditional types, generic types, type guards, advanced types, and more. You can use them to build a well-constrained type system to make your app strongly typed. This can’t be achieved by the interface.

In many cases, they can be used interchangeably depending on personal preference. But, we should use type aliases in the following use cases:

  • To create a new name for a primitive type
  • To define a union type, tuple type, function type, or another more complex type
  • To overload functions
  • To use mapped types, conditional types, type guard, or other advanced type features

Compared with interfaces, types are more expressive. There are many advanced type features that are not available in interfaces, and those features continue to grow as TypeScript evolves.

In addition, many developers prefer to use types because they are a good match with the functional programming paradigm. The rich type expression makes it easier to achieve functional composition, immutability, and other functional programming capabilities in a type-safe manner.

Summary

In this article, we discussed type aliases and interfaces, as well as their differences. While there are some scenarios in which one is preferred over the other, in most cases, the choice between them boils down to personal preference.

I lean towards using types, simply because of the amazing type system. What are your preferences? You are welcome to share your opinions in the comments section below.

Source: https://blog.logrocket.com

#typescript 

What is GEEK

Buddha Community

Types vs Interfaces in TypeScript
Verdie  Murray

Verdie Murray

1636240140

What Is The Main Difference Of TYPES Vs INTERFACES in TypeScript

TypeScript has two ways of declaring structures of your objects in the form of  #types (type aliases) and #interfaces.

In this lesson we will look at the technical differences between these two, when you should use which, along with real world #TypeScript code analysis, and community thoughts

#typescript 

The Definitive Guide to TypeScript & Possibly The Best TypeScript Book

TypeScript Deep Dive

I've been looking at the issues that turn up commonly when people start using TypeScript. This is based on the lessons from Stack Overflow / DefinitelyTyped and general engagement with the TypeScript community. You can follow for updates and don't forget to ★ on GitHub 🌹

Reviews

  • Thanks for the wonderful book. Learned a lot from it. (link)
  • Its probably the Best TypeScript book out there. Good Job (link)
  • Love how precise and clear the examples and explanations are! (link)
  • For the low, low price of free, you get pages of pure awesomeness. Chock full of source code examples and clear, concise explanations, TypeScript Deep Dive will help you learn TypeScript development. (link)
  • Just a big thank you! Best TypeScript 2 detailed explanation! (link)
  • This gitbook got my project going pronto. Fluent easy read 5 stars. (link)
  • I recommend the online #typescript book by @basarat you'll love it.(link)
  • I've always found this by @basarat really helpful. (link)
  • We must highlight TypeScript Deep Dive, an open source book.(link)
  • Great online resource for learning. (link)
  • Thank you for putting this book together, and for all your hard work within the TypeScript community. (link)
  • TypeScript Deep Dive is one of the best technical texts I've read in a while. (link)
  • Thanks @basarat for the TypeScript Deep Dive Book. Help me a lot with my first TypeScript project. (link)
  • Thanks to @basarat for this great #typescript learning resource. (link)
  • Guyz excellent book on Typescript(@typescriptlang) by @basarat (link)
  • Leaning on the legendary @basarat's "TypeScript Deep Dive" book heavily at the moment (link)
  • numTimesPointedPeopleToBasaratsTypeScriptBook++; (link)
  • A book not only for typescript, a good one for deeper JavaScript knowledge as well. link
  • In my new job, we're using @typescriptlang, which I am new to. This is insanely helpful huge thanks, @basarat! link
  • Thank you for writing TypeScript Deep Dive. I have learned so much. link
  • Loving @basarat's @typescriptlang online book basarat.gitbooks.io/typescript/# loaded with great recipes! link
  • Microsoft doc is great already, but if want to "dig deeper" into TypeScript I find this book of great value link
  • Thanks, this is a great book 🤓🤓 link
  • Deep dive to typescript is awesome in so many levels. i find it very insightful. Thanks link
  • @basarat's intro to @typescriptlang is still one of the best going (if not THE best) link
  •  
  • This is sweet! So many #typescript goodies! link

Get Started

If you are here to read the book online get started.

Translations

Book is completely free so you can copy paste whatever you want without requiring permission. If you have a translation you want me to link here. Send a PR.

Other Options

You can also download one of the Epub, Mobi, or PDF formats from the actions tab by clicking on the latest build run. You will find the files in the artifacts section.

Special Thanks

All the amazing contributors 🌹

Share

Share URL: https://basarat.gitbook.io/typescript/

Author: Basarat
Source Code: https://github.com/basarat/typescript-book/ 
License: View license

#typescript #opensource 

Jadyn  Waelchi

Jadyn Waelchi

1626695700

Typescript Types vs Interfaces

Typescript types vs interfaces what are the differences. There are two different ways in TypeScript to declare object types: Interfaces and type aliases. In this video I will tell you what the differences are and when you want to use what.

#typescript #interfaces

Autumn  Blick

Autumn Blick

1598839687

How native is React Native? | React Native vs Native App Development

If you are undertaking a mobile app development for your start-up or enterprise, you are likely wondering whether to use React Native. As a popular development framework, React Native helps you to develop near-native mobile apps. However, you are probably also wondering how close you can get to a native app by using React Native. How native is React Native?

In the article, we discuss the similarities between native mobile development and development using React Native. We also touch upon where they differ and how to bridge the gaps. Read on.

A brief introduction to React Native

Let’s briefly set the context first. We will briefly touch upon what React Native is and how it differs from earlier hybrid frameworks.

React Native is a popular JavaScript framework that Facebook has created. You can use this open-source framework to code natively rendering Android and iOS mobile apps. You can use it to develop web apps too.

Facebook has developed React Native based on React, its JavaScript library. The first release of React Native came in March 2015. At the time of writing this article, the latest stable release of React Native is 0.62.0, and it was released in March 2020.

Although relatively new, React Native has acquired a high degree of popularity. The “Stack Overflow Developer Survey 2019” report identifies it as the 8th most loved framework. Facebook, Walmart, and Bloomberg are some of the top companies that use React Native.

The popularity of React Native comes from its advantages. Some of its advantages are as follows:

  • Performance: It delivers optimal performance.
  • Cross-platform development: You can develop both Android and iOS apps with it. The reuse of code expedites development and reduces costs.
  • UI design: React Native enables you to design simple and responsive UI for your mobile app.
  • 3rd party plugins: This framework supports 3rd party plugins.
  • Developer community: A vibrant community of developers support React Native.

Why React Native is fundamentally different from earlier hybrid frameworks

Are you wondering whether React Native is just another of those hybrid frameworks like Ionic or Cordova? It’s not! React Native is fundamentally different from these earlier hybrid frameworks.

React Native is very close to native. Consider the following aspects as described on the React Native website:

  • Access to many native platforms features: The primitives of React Native render to native platform UI. This means that your React Native app will use many native platform APIs as native apps would do.
  • Near-native user experience: React Native provides several native components, and these are platform agnostic.
  • The ease of accessing native APIs: React Native uses a declarative UI paradigm. This enables React Native to interact easily with native platform APIs since React Native wraps existing native code.

Due to these factors, React Native offers many more advantages compared to those earlier hybrid frameworks. We now review them.

#android app #frontend #ios app #mobile app development #benefits of react native #is react native good for mobile app development #native vs #pros and cons of react native #react mobile development #react native development #react native experience #react native framework #react native ios vs android #react native pros and cons #react native vs android #react native vs native #react native vs native performance #react vs native #why react native #why use react native

Arvel  Parker

Arvel Parker

1593156510

Basic Data Types in Python | Python Web Development For Beginners

At the end of 2019, Python is one of the fastest-growing programming languages. More than 10% of developers have opted for Python development.

In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.

Table of Contents  hide

I Mutable objects

II Immutable objects

III Built-in data types in Python

Mutable objects

The Size and declared value and its sequence of the object can able to be modified called mutable objects.

Mutable Data Types are list, dict, set, byte array

Immutable objects

The Size and declared value and its sequence of the object can able to be modified.

Immutable data types are int, float, complex, String, tuples, bytes, and frozen sets.

id() and type() is used to know the Identity and data type of the object

a**=25+**85j

type**(a)**

output**:<class’complex’>**

b**={1:10,2:“Pinky”****}**

id**(b)**

output**:**238989244168

Built-in data types in Python

a**=str(“Hello python world”)****#str**

b**=int(18)****#int**

c**=float(20482.5)****#float**

d**=complex(5+85j)****#complex**

e**=list((“python”,“fast”,“growing”,“in”,2018))****#list**

f**=tuple((“python”,“easy”,“learning”))****#tuple**

g**=range(10)****#range**

h**=dict(name=“Vidu”,age=36)****#dict**

i**=set((“python”,“fast”,“growing”,“in”,2018))****#set**

j**=frozenset((“python”,“fast”,“growing”,“in”,2018))****#frozenset**

k**=bool(18)****#bool**

l**=bytes(8)****#bytes**

m**=bytearray(8)****#bytearray**

n**=memoryview(bytes(18))****#memoryview**

Numbers (int,Float,Complex)

Numbers are stored in numeric Types. when a number is assigned to a variable, Python creates Number objects.

#signed interger

age**=**18

print**(age)**

Output**:**18

Python supports 3 types of numeric data.

int (signed integers like 20, 2, 225, etc.)

float (float is used to store floating-point numbers like 9.8, 3.1444, 89.52, etc.)

complex (complex numbers like 8.94j, 4.0 + 7.3j, etc.)

A complex number contains an ordered pair, i.e., a + ib where a and b denote the real and imaginary parts respectively).

String

The string can be represented as the sequence of characters in the quotation marks. In python, to define strings we can use single, double, or triple quotes.

# String Handling

‘Hello Python’

#single (') Quoted String

“Hello Python”

# Double (") Quoted String

“”“Hello Python”“”

‘’‘Hello Python’‘’

# triple (‘’') (“”") Quoted String

In python, string handling is a straightforward task, and python provides various built-in functions and operators for representing strings.

The operator “+” is used to concatenate strings and “*” is used to repeat the string.

“Hello”+“python”

output**:****‘Hello python’**

"python "*****2

'Output : Python python ’

#python web development #data types in python #list of all python data types #python data types #python datatypes #python types #python variable type