Typescript Tutorial: Type Assertions & Type Casting

Learn Type Assertions & Type Casting in this Typescript tutorial for beginners. Learn more about type assertions and type casting and complete a Typescript student challenge in detailed TS tutorial.

Type Assertions & Type Casting | Typescript Tutorial for Beginners

(00:00) Intro
(00:05) Welcome
(00:28) Type Assertions vs Type Casting
(01:18) What are Type Assertions?
(01:58) Starter Code
(03:44) Converting Types with Assertions
(04:53) Angle Bracket Syntax instead of "as"
(05:55) Narrowing Return Values with Assertions
(08:37) Caution: Assertions allow mistakes!
(10:07) Double Casting and the unknown type
(12:03) DOM Selection Types
(16:19) Non-Null Assertions
(17:43) Angle Brackets and the DOM
(18:14) Student Challenge
(21:27) Solution 1: Beginners
(24:13) Solution 2: Type Assertion

Corrections: 
(13:50) Syntax error: document.getElementById('img') is what is needed if the element has an id set to "img". This does not change the concept I'm discussing. Just tired eyes and a syntax error.


Type Casting

in this tutorial, you will learn about type castings in TypeScript, which allow you to convert a variable from one type to another type.

JavaScript doesn’t have a concept of type casting because variables have dynamic types. However, every variable in TypeScript has a type. Type castings allow you to convert a variable from one type to another.

In TypeScript, you can use the as keyword or <> operator for type castings.

Type casting using the as keyword

The following selects the first input element by using the querySelector() method:

let input = document.querySelector('input["type="text"]');

Code language: TypeScript (typescript)

Since the returned type of the document.querySelector() method is the Element type, the following code causes a compiler error:

console.log(input.value);

Code language: TypeScript (typescript)

The reason is that the value property doesn’t exist in the Element type. It only exists on the HTMLInputElement type.

To resolve this, you can use type casting that cast the Element to HTMLInputElement by using the as keyword like this:

let input = document.querySelector('input[type="text"]') as HTMLInputElement;

Code language: TypeScript (typescript)

Now, the input variable has the type HTMLInputElement. So accessing its value property won’t cause any error. The following code works:

console.log(input.value);

Code language: TypeScript (typescript)

Another way to cast the Element to HTMLInputElement is when you access the property as follows:

let enteredText = (input as HTMLInputElement).value;

Code language: TypeScript (typescript)

Note that the HTMLInputElement type extends the HTMLElement type that extends to the Element type. When you cast the HTMLElement to HTMLInputElement, this type casting is also known as a down casting.

It’s also possible to carry an down casting. For example:

let el: HTMLElement;
el = new HTMLInputElement();

In this example, the el variable has the HTMLElement type. And you can assign it an instance of HTMLInputElement type because the HTMLInputElement type is an subclass of the HTMLElement type.

The syntax for converting a variable from typeA to typeB is as follows:

let a: typeA;
let b = a as typeB;

Type Casting using the <> operator

Besides the as keyword, you can use the <> operator to carry a type casting. For example:

let input = <HTMLInputElement>document.querySelector('input[type="text"]');

console.log(input.value);

The syntax for type casting using the <> is:

let a: typeA;
let b = <typeB>a;

Summary

  • Type casting allows you to convert a variable from one type to another.
  • Use the as keyword or <> operator for type castings.

Explain Type assertions in TypeScript

In Typescript, Type assertion is a technique that informs the compiler about the type of a variable. Type assertion is similar to typecasting but it doesn’t reconstruct code. You can use type assertion to specify a value’s type and tell the compiler not to deduce it. When we want to change a variable from one type to another such as any to number etc, we use Type assertion. 

We can either use <> angular brackets or as keywords to do type assertion. When we migrate code from typescript to another language type assertion comes into play. Runtime support comes with typecasting, whereas type assertion has no effect on runtime. It is used by the compiler. 

Example 1: Type assertion using syntax

In this example, we give assign the ‘geeksforgeeks’ string to a variable of type unknown. We further assign the value of the string to another variable and calculate the length of the string. In the below code we have asserted that str is of type number by using the “as” keyword. 

let str: unknown = "geeksforgeeks";
console.log(str);

let len: number = (str as string).length;
console.log(len);

Output:

geeksforgeeks
13

Example 2: Type assertion using <> angle brackets syntax

This example is similar to the before one, we assign a number to a variable of type any and then assign the value to another variable and we have asserted that the num variable is of type “Number”. We used <> angle brackets instead of keywords.

let num: any = 77;

// Conversion from any to number
let num1 = <Number> num;

console.log(num1);
console.log(typeof num1);

Output:

77
number

Example 3: Type assertion for objects

We may occasionally encounter a circumstance in which an object is defined without any properties. The compiler throws an error as a result of this. However, we may prevent this issue by utilizing type assertion. With the help of the following example, we can comprehend it.

interface details {}
details.first_name = "Sarah";
details.last_name = "jane";

Output:

error TS2693: 'details' only refers to a type, but is being used as a value here.
details.first_name = "Sarah";

After defining parameters, the compiler doesn’t throw an error. Compiler raises an error in the before example as it cannot find any properties within the object. Type assertion helps us resolve such errors. We used type assertion on details.

interface details {
	first_name: string;
	last_name: string;
}

let person_1 = <details>{};
person_1.first_name = "Sarah";
person_1.last_name = "jane";

console.log(person_1);

Output:

{ first_name: 'Sarah', last_name: 'jane' }

#typescript #javascript #programming 

What is GEEK

Buddha Community

Typescript Tutorial: Type Assertions & Type Casting

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 

Macey  Legros

Macey Legros

1600075200

Java Type Casting Example | Type Casting In Java Tutorial

Let’s say you want to assign the value of one data type into another variable of another data type, so there might be a case that they are not compatible with each other. To overcome this problem, we have one solution that we are going to learn today, called ‘Type Casting’ In Java, if both data types are compatible with each other, then it automatically has done its conversion, which is known as ‘Automatic type conversion.’

Java Type Casting

Typecasting is used to convert an object or variable of one type into another.

There are two types of typecasting in Java they are:

  1. Implicit Type Casting, known as Widening Type Casting
  2. Explicit Type Casting, also known as Narrowing Type Casting

We will learn about these two types of typecasting.

#java #java type casting #type casting

Willie  Beier

Willie Beier

1596728880

Tutorial: Getting Started with R and RStudio

In this tutorial we’ll learn how to begin programming with R using RStudio. We’ll install R, and RStudio RStudio, an extremely popular development environment for R. We’ll learn the key RStudio features in order to start programming in R on our own.

If you already know how to use RStudio and want to learn some tips, tricks, and shortcuts, check out this Dataquest blog post.

Table of Contents

#data science tutorials #beginner #r tutorial #r tutorials #rstats #tutorial #tutorials

Tutorial: Loading and Cleaning Data with R and the tidyverse

1. Characteristics of Clean Data and Messy Data

What exactly is clean data? Clean data is accurate, complete, and in a format that is ready to analyze. Characteristics of clean data include data that are:

  • Free of duplicate rows/values
  • Error-free (e.g. free of misspellings)
  • Relevant (e.g. free of special characters)
  • The appropriate data type for analysis
  • Free of outliers (or only contain outliers have been identified/understood), and
  • Follows a “tidy data” structure

Common symptoms of messy data include data that contain:

  • Special characters (e.g. commas in numeric values)
  • Numeric values stored as text/character data types
  • Duplicate rows
  • Misspellings
  • Inaccuracies
  • White space
  • Missing data
  • Zeros instead of null values

2. Motivation

In this blog post, we will work with five property-sales datasets that are publicly available on the New York City Department of Finance Rolling Sales Data website. We encourage you to download the datasets and follow along! Each file contains one year of real estate sales data for one of New York City’s five boroughs. We will work with the following Microsoft Excel files:

  • rollingsales_bronx.xls
  • rollingsales_brooklyn.xls
  • rollingsales_manhattan.xls
  • rollingsales_queens.xls
  • rollingsales_statenisland.xls

As we work through this blog post, imagine that you are helping a friend launch their home-inspection business in New York City. You offer to help them by analyzing the data to better understand the real-estate market. But you realize that before you can analyze the data in R, you will need to diagnose and clean it first. And before you can diagnose the data, you will need to load it into R!

3. Load Data into R with readxl

Benefits of using tidyverse tools are often evident in the data-loading process. In many cases, the tidyverse package readxl will clean some data for you as Microsoft Excel data is loaded into R. If you are working with CSV data, the tidyverse readr package function read_csv() is the function to use (we’ll cover that later).

Let’s look at an example. Here’s how the Excel file for the Brooklyn borough looks:

The Brooklyn Excel file

Now let’s load the Brooklyn dataset into R from an Excel file. We’ll use the readxlpackage. We specify the function argument skip = 4 because the row that we want to use as the header (i.e. column names) is actually row 5. We can ignore the first four rows entirely and load the data into R beginning at row 5. Here’s the code:

library(readxl) # Load Excel files
brooklyn <- read_excel("rollingsales_brooklyn.xls", skip = 4)

Note we saved this dataset with the variable name brooklyn for future use.

4. View the Data with tidyr::glimpse()

The tidyverse offers a user-friendly way to view this data with the glimpse() function that is part of the tibble package. To use this package, we will need to load it for use in our current session. But rather than loading this package alone, we can load many of the tidyverse packages at one time. If you do not have the tidyverse collection of packages, install it on your machine using the following command in your R or R Studio session:

install.packages("tidyverse")

Once the package is installed, load it to memory:

library(tidyverse)

Now that tidyverse is loaded into memory, take a “glimpse” of the Brooklyn dataset:

glimpse(brooklyn)
## Observations: 20,185
## Variables: 21
## $ BOROUGH <chr> "3", "3", "3", "3", "3", "3", "…
## $ NEIGHBORHOOD <chr> "BATH BEACH", "BATH BEACH", "BA…
## $ `BUILDING CLASS CATEGORY` <chr> "01 ONE FAMILY DWELLINGS", "01 …
## $ `TAX CLASS AT PRESENT` <chr> "1", "1", "1", "1", "1", "1", "…
## $ BLOCK <dbl> 6359, 6360, 6364, 6367, 6371, 6…
## $ LOT <dbl> 70, 48, 74, 24, 19, 32, 65, 20,…
## $ `EASE-MENT` <lgl> NA, NA, NA, NA, NA, NA, NA, NA,…
## $ `BUILDING CLASS AT PRESENT` <chr> "S1", "A5", "A5", "A9", "A9", "…
## $ ADDRESS <chr> "8684 15TH AVENUE", "14 BAY 10T…
## $ `APARTMENT NUMBER` <chr> NA, NA, NA, NA, NA, NA, NA, NA,…
## $ `ZIP CODE` <dbl> 11228, 11228, 11214, 11214, 112…
## $ `RESIDENTIAL UNITS` <dbl> 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1…
## $ `COMMERCIAL UNITS` <dbl> 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0…
## $ `TOTAL UNITS` <dbl> 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1…
## $ `LAND SQUARE FEET` <dbl> 1933, 2513, 2492, 1571, 2320, 3…
## $ `GROSS SQUARE FEET` <dbl> 4080, 1428, 972, 1456, 1566, 22…
## $ `YEAR BUILT` <dbl> 1930, 1930, 1950, 1935, 1930, 1…
## $ `TAX CLASS AT TIME OF SALE` <chr> "1", "1", "1", "1", "1", "1", "…
## $ `BUILDING CLASS AT TIME OF SALE` <chr> "S1", "A5", "A5", "A9", "A9", "…
## $ `SALE PRICE` <dbl> 1300000, 849000, 0, 830000, 0, …
## $ `SALE DATE` <dttm> 2020-04-28, 2020-03-18, 2019-0…

The glimpse() function provides a user-friendly way to view the column names and data types for all columns, or variables, in the data frame. With this function, we are also able to view the first few observations in the data frame. This data frame has 20,185 observations, or property sales records. And there are 21 variables, or columns.

#data science tutorials #beginner #r #r tutorial #r tutorials #rstats #tidyverse #tutorial #tutorials

Jeromy  Lowe

Jeromy Lowe

1599097440

Data Visualization in R with ggplot2: A Beginner Tutorial

A famous general is thought to have said, “A good sketch is better than a long speech.” That advice may have come from the battlefield, but it’s applicable in lots of other areas — including data science. “Sketching” out our data by visualizing it using ggplot2 in R is more impactful than simply describing the trends we find.

This is why we visualize data. We visualize data because it’s easier to learn from something that we can see rather than read. And thankfully for data analysts and data scientists who use R, there’s a tidyverse package called ggplot2 that makes data visualization a snap!

In this blog post, we’ll learn how to take some data and produce a visualization using R. To work through it, it’s best if you already have an understanding of R programming syntax, but you don’t need to be an expert or have any prior experience working with ggplot2

#data science tutorials #beginner #ggplot2 #r #r tutorial #r tutorials #rstats #tutorial #tutorials