Modesto  Corwin

Modesto Corwin

1620527220

Enums and Literal Types in Typescript - No BS TS #11

Lets export enumerations and literal types in Typescript and show how they can make your code safer.

  • 00:00 Introduction
  • 01:23 Enumerations
  • 03:19 Literal types
  • 04:55 Numeric literals
  • 06:02 String literals
  • 07:11 Outroduction

Code: https://github.com/jherr/no-bs-ts/tree/master/episode-11

#typescript

Enums and Literal Types in Typescript - No BS TS #11
Modesto  Corwin

Modesto Corwin

1620527220

Enums and Literal Types in Typescript - No BS TS #11

Lets export enumerations and literal types in Typescript and show how they can make your code safer.

  • 00:00 Introduction
  • 01:23 Enumerations
  • 03:19 Literal types
  • 04:55 Numeric literals
  • 06:02 String literals
  • 07:11 Outroduction

Code: https://github.com/jherr/no-bs-ts/tree/master/episode-11

#typescript

Enums and Literal Types in Typescript - No BS TS #11
Suparnar Taina

Suparnar Taina

1582263000

What is Enum in Typescript?

Introduction

In this article you will learn about Enum in Typescript in detail. This article will help beginners to understand the concept.

What is Enum?

  • The short form of enumeration is enum.
  • It is used as a type with some set of values called a named constant.
  • Inernally it holds numeric type values or in some cases we can create heterogeneous enums.
  • The enum keyword is used to define the enums.
  • We can create a distinct case so it makes it easy to document.
  • It forces us to use all possible values.
  • Access the enums using index or use dot operator after the enum name & named constant.
  • Initial value starts from 0 if we do not set any value.
  • Auto incremental is the best approach to use because we do not need to worry about the values.

Syntax

enum enumName{  
constant1, constant2, constant3...  
}  

Example

Consider  traffic signal lights as an example.

This is image title

We can access the elements using index or by constant name:

enum signalLights{  
   red, yellow, green  
}  
let result: string = signalLights[signalLights.red];  
console.log(result);  
console.log(signalLights[1]);  
let output: signalLights = (<any>signalLights)["yellow"];  
console.log(output);  

Output

red
yellow
1

Types of enums

Numeric enum

  • It is commonly used in all languages.
  • Initial value starts from 0 if we do not set any value.
  • Takes only numeric values.
  • enum keyword is used to declare the numeric type enum.
  • We can assign any value as per our requirements.
  • If our function returns any numeric value then we can use this function to initialize the constant.

Consider that in the below rainbowColors is enum & we have not initialized any constants, so it will starts with 0 value and the rest of the constants have auto increamemtal values.

**Example **

enum rainbowColors {  
    Red,  
    Orange,  
    Yellow,  
    Green,  
    Blue,  
    Indigo,  
    Violet,  
}  
console.log("color & index value is as follows");  
for (let item in rainbowColors) {  
    if (isNaN(Number(item))) {  
        console.log(item + " : " + < rainbowColors > rainbowColors[item]);  
    }  
}   

Output

color & index value is as follows:

Red : 0
Orange : 1
Yellow : 2
Green : 3
Blue : 4
Indigo : 5
Violet : 6

Consider the below example, rainbowColors is enum & the second element is initialized with value 1000. So it will be auto incremental to the  remaining constants. It will print on the console.

**Example **

enum rainbowColors {  
    Red,  
    Orange = 1000,  
    Yellow,  
    Green,  
    Blue,  
    Indigo,  
    Violet,  
}  
console.log("color & index value is as follows");  
for (let item in rainbowColors) {  
    if (isNaN(Number(item))) {  
        console.log(item + " : " + < rainbowColors > rainbowColors[item]);  
    }  
}   

Output

color & index value is as follows,

Red : 0
Orange : 1000
Yellow : 1001
Green : 1002
Blue : 1003
Indigo : 1004
Violet : 1005

Using function in enum

Consider the below example. We can use function in enum if we are returning the value from the function. It is used when the user needs to do any calculation. Suppose we need to calculate the total minutes like 1 hour = 60 minute, 2 hour = 120 minute, then it will create one function which will do a calcuation & return values to enum constant:

Example

function Totalminute(hr: number): any{  
return 60 * hr;  
}  
enum hours  
{  
One = Totalminute(1) ,  
Two = Totalminute(2),  
Three = Totalminute(4),  
}  
console.log(hours.One);  
console.log(hours.Two);  
console.log(hours.Three);  

Output

60
120
240

String enum

It is same as the numeric enums,  we are just passing string values/literals to our enum constant. enum keyword is used to declare the enums.

Consider the below example, our vehicle is taking different kinds of turns, and we will define the enum as:

Example

enum vehicleTurn {  
    Left = "Left",  
        Right = "Right",  
        UTurn = "UTurn"  
}  
console.log(vehicleTurn.Left);  
console.log(vehicleTurn.Right);  
console.log(vehicleTurn.UTurn);  
}   

Output

Left
Right
UTurn

Heterogeneous enums

Typescript allows us to create a mixed type of enums.

This means we can assign numeric & string type values to enum.

Consider the below example, circleInfo has heterogeneous enum values.

Example

enum circleInfo {  
    Area = "area of circle",  
        Pie = 3.112,  
        Radius = 20  
}  
let result = circleInfo.Pie * circleInfo.Radius * circleInfo.Radius;  
console.log(circleInfo.Area + " is :" + result); 

Output

area of circle is :1244.8

Point A - Function & interface using enum

Consider the below example, clothSize is enum which contains some constants. IClothSize is an interface which contains two properties, key & value, having string & number type respectively.

Function is taking enum as a parameter & will print the data on the console.

Example

enum clothSize {  
    small,  
    medium,  
    large  
}  
interface IClothSize {  
    key: string,  
        value: number  
}  
  
function getClothSize(size: clothSize): IClothSize {  
    switch (size) {  
        case clothSize.small:  
            return {  
                key: clothSize[clothSize.small], value: 10  
            };  
        case clothSize.medium:  
            return {  
                key: clothSize[clothSize.medium], value: 20  
            };  
        case clothSize.large:  
            return {  
                key: clothSize[clothSize.large], value: 30  
            };  
    }  
}  
console.log("cloth is " + getClothSize(clothSize.small).key + " & value is " + getClothSize(clothSize.small).value);  
console.log("cloth is " + getClothSize(clothSize.medium).key + " & value is " + getClothSize(clothSize.medium).value);  

Output

cloth is small & value is 10

cloth is medium & value is 20

Point B - const enum

  • Typescript allows us to declare const enum.
  • const keyword is used.
  • It has a inlined values.
  • We can access enum using enum[‘ConstantName’]

Example

const enum myColor {  
    Red = 10,  
        White = Red * 4,  
        Blue = White + 10,  
        Yellow,  
}  
console.log(myColor.Red)  
console.log(myColor.White)  
console.log(myColor.Blue)  
console.log(myColor['Yellow'])   

Output

10
40
50
51

We will not be able to access enum using index in const enum like myColor[0], it will give us an error.

Point C

ES6 allows us to use map enum keys.

Example

enum classes {  
    I,  
    II,  
    III,  
    IV,  
    V  
}  
const ClassNames = new Map < number,  
    string > ([  
        [classes.I, '100'],  
        [classes.II, '200'],  
        [classes.III, '300'],  
    ]);  
console.log(ClassNames);   

Output

Map(3) {0 => “100”, 1 => “200”, 2 => “300”}

We will modify the above example, we can use this into a classes as below.

Note

User can modify the code as per their requirement.

Example

enum classes {  
    I,  
    II,  
    III,  
    IV,  
    V  
}  
const ClassNames = new Map < number,  
    string > ([  
        [classes.I, '100'],  
        [classes.II, '200'],  
        [classes.III, '300'],  
    ]);  
class AllStandards {  
    public allNames: object;  
    constructor() {  
        this.allNames = ClassNames;  
    }  
}  
let obj: AllStandards = new AllStandards();  
console.log(obj.allNames);   

Output

Map(3) {0 => “100”, 1 => “200”, 2 => “300”}

Point D - export enum

  • typescript allows us to export the enum.
  • export keyword is used before the enum.
  • import is used to import that enum file.

We can declare the enum like this:

export enum sportActivities {Football, Cricket,Badminton, Tennis}  

To import the enum in .ts,  i.e.; typescript file looks like this:

import {sportActivities} from '../enums'  

Summary

In this article, you learned about enum in Typescript. Thanks for reading!

#typescript #angular #Enum in Typescript

What is Enum in Typescript?
Myah  Conn

Myah Conn

1591368300

TypeScript Tutorial #11 - The DOM and Type Casting

TypeScript Tutorial #11 - The DOM and Type Casting

#typescript #type #dom

TypeScript Tutorial #11 - The DOM and Type Casting
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

Basic Data Types in Python | Python Web Development For Beginners
Christa  Stehr

Christa Stehr

1599315360

Nominal typing in Typescript

Nominal & structural typing

Type systems are typically categorized as either structural or nominal. Languages like Java and Scala have primarily nominal type systems, whereas a language like Typescript has a structural type system. Let’s take a brief look at both systems.

Nominal Typing

In a nominal typing system, type compatibility is checked using the name of the types. If they do not have the same name, then they are not compatible; end of story. **If **Typescript had a nominal typing system the type check for the last line would fail:

Image for post

Structural typing

Typescript uses structural typing to decide whether two types are compatible with one another or not. What do we mean by structural typing? Well, let’s consider the following code snippet:

Image for post

To determine whether the type of the constant color(RGBA) is compatible with the type of serializeColor’s parameter x(RGB) the type system must verify that each member of RGB has a corresponding compatible member in RGBA. In this case, RGB has a single member color for which RGBA has a corresponding member with the same type — [number, number, number] — and so it passes the type check. Notice how the type system ignores the additional members that exist on RGBA (alpha).

#typescript #type-safe #type-systems

Nominal typing in Typescript