- TypeScript
- Таблица типов в Typescript
- Type assertion
- Jenerics
- Utility Types
- Download TypeScript
- TypeScript in Your Project
- via npm
- with Visual Studio
- Globally Installing TypeScript
- via npm
- via Visual Studio Marketplace
- Working with TypeScript-compatible transpilers
- Babel
- Sucrase
- TypeScript: What is it & when is it useful?
- An introduction to the programming language TypeScript and why you might want to learn it.
- What is it?
- Who created it and why?
- What is static type checking and how does TypeScript implement it?
- Assigning types in TypeScript
- Using interfaces to describe objects with properties
- Defining classes
- What else can TypeScript do?
- Who’s using TypeScript?
- Вводный курс по TypeScript
- Стоит ли использовать TypeScript?
- В каких случаях стоит использовать TypeScript?
- Установка TypeScript
- Типы переменных
- Number
- String
- Boolean
- Присвоение типов
- Одиночный тип переменной
- Мультитип переменной
- Проверка типов
- Typeof
- Instanceof
- Тип Assertions
- Ключевое слово as
- Оператор <>
TypeScript
TypeScript — язык программирования, представленный Microsoft в 2012 году и позиционируемый как средство разработки веб-приложений, расширяющее возможности JavaScript.
Разработчиком языка TypeScript является Андерс Хейлсберг (англ. Anders Hejlsberg), создавший ранее Turbo Pascal, Delphi и C#.
TypeScript является обратно совместимым с JavaScript и компилируется в последний. Фактически, после компиляции программу на TypeScript можно выполнять в любом современном браузере или использовать совместно с серверной платформой Node.js. Код экспериментального компилятора, транслирующего TypeScript в JavaScript, распространяется под лицензией Apache. Его разработка ведётся в публичном репозитории через сервис GitHub.
TypeScript отличается от JavaScript возможностью явного статического назначения типов, поддержкой использования полноценных классов (как в традиционных объектно-ориентированных языках).
tsconfig. json представляет собой стандартный файл в формате json, который содержит ряд секций. Например:
Таблица типов в Typescript
TypeScript является строго типизированным языком, и каждая переменная и константа в нем имеет определенный тип. При этом в отличие от javascript мы не можем динамически изменить ранее указанный тип переменной.
В TypeScript имеются следующие базовые типы:
- Boolean: логическое значение true или false
- Number: числовое значение
- String: строки
- Array: массивы
- Tuple: кортежи
- Enum: перечисления
- Any: произвольный тип
- Null и undefined: соответствуют значениям null и undefined в javascript
- Void: отсутствие конкретного значения, используется в основном в качестве возвращаемого типа функций
- Never: также представляет отсутствие значения и используется в качестве возвращаемого типа функций, которые генерируют или возвращают ошибку
Type assertion
Type assertion представляет модель преобразования значения переменной к определенному типу. Обычно в некоторых ситуациях одна переменная может представлять какой-то широкий тип, например, any, который по факту допускает значения различных типов. Однако при этом нам надо использовать переменную как значение строго определенного типа. И в этом случае мы можем привести к этому типу.
Есть две формы приведения. Первая форма заключается в использовании угловых скобок:
Вторая форма заключается в применении оператора as:
Jenerics
TypeScript является строго типизированным языком, однако иногда надо построить функционал так, чтобы он мог использовать данные любых типов. В некоторых случаях мы могли бы использовать тип any:
Однако в этом случае мы не можем использовать результат функции как объект того типа, который передан в функцию. Для нас это тип any. Если бы вместо числа 5 в функцию передавался бы объект какого-нибудь класса, и нам потом надо было бы использовать этот объект, например, вызывать у него функции, то это было бы проблематично. И чтобы конкретизировать возвращаемый тип, мы можем использовать обобщения:
Utility Types
Typescript поставляет объекты при помощи которых можно легко проводить трансформацию типов, например:
Requared — создаёт тип, в котором все поля обязательные
Readonly — все поля не могут быть изменены
ReturnType — Создает тип, состоящий из типа, возвращаемого функцией Type.
Источник
Download TypeScript
TypeScript can be installed through three installation routes depending on how you intend to use it: an npm module, a NuGet package or a Visual Studio Extension.
If you are using Node.js, you want the npm version. If you are using MSBuild in your project, you want the NuGet package or Visual Studio extension.
TypeScript in Your Project
Having TypeScript set up on a per-project basis lets you have many projects with many different versions of TypeScript, this keeps each project working consistently.
via npm
TypeScript is available as a package on the npm registry available as «typescript» .
You will need a copy of Node.js as an environment to run the package. Then you use a dependency manager like npm, yarn or pnpm to download TypeScript into your project.
npm install typescript —save-dev
All of these dependency managers support lockfiles, ensuring that everyone on your team is using the same version of the language. You can then run the TypeScript compiler using one of the following commands:
with Visual Studio
For most project types, you can get TypeScript as a package in Nuget for your MSBuild projects, for example an ASP.NET Core app.
- The Manage NuGet Packages window (which you can get to by right-clicking on a project node)
- The Nuget Package Manager Console (found in Tools > NuGet Package Manager > Package Manager Console) and then running:
Install-Package Microsoft.TypeScript.MSBuild
For project types which don’t support Nuget, you can use the TypeScript Visual Studio extension. You can install the extension using Extensions > Manage Extensions in Visual Studio.
The examples below are for more advanced use cases.
Globally Installing TypeScript
It can be handy to have TypeScript available across all projects, often to test one-off ideas. Long-term, codebases should prefer a project-wide installation over a global install so that they can benefit from reproducible builds across different machines.
via npm
You can use npm to install TypeScript globally, this means that you can use the tsc command anywhere in your terminal.
To do this, run npm install -g typescript . This will install the latest version (currently 4.4 ).
An alternative is to use npx when you have to run tsc for one-off occasions.
via Visual Studio Marketplace
You can install TypeScript as a Visual Studio extension, which will allow you to use TypeScript across many MSBuild projects in Visual Studio.
Working with TypeScript-compatible transpilers
There are other tools which convert TypeScript files to JavaScript files. You might use these tools for speed or consistency with your existing build tooling.
Each of these projects handle the file conversion, but do not handle the type-checking aspects of the TypeScript compiler. So it’s likely that you will still need to keep the above TypeScript dependency around, and you will want to enable isolatedModules .
Babel
Babel is a very popular JavaScript transpiler which supports TypeScript files via the plugin @babel/plugin-transform-typescript.
swc is a fast transpiler created in Rust which supports many of Babel’s features including TypeScript.
Sucrase
Sucrase is a Babel fork focused on speed for using in development mode. Sucrase supports TypeScript natively.
Источник
TypeScript: What is it & when is it useful?
An introduction to the programming language TypeScript and why you might want to learn it.
What is it?
TypeScript is a superset of JavaScript, meaning that it contains all of the functionality of JavaScript and then some. Therefore, any program written in valid JavaScript will also run as expected in TypeScript. In fact, TypeScript compiles simply to plain JavaScript. So, what’s the difference? TypeScript offers us more control over our code via type annotations, interfaces, and classes. I’ll explain each of these later.
Who created it and why?
TypeScript was created by Microsoft and was released in 2012 after two years of development. It was created to allow for optional static type checking, which would be particularly useful when developing large scale applications. Interestingly, one of the reasons Microsoft developed TypeScript was because their internal teams were having trouble making JavaScript scale for Microsoft’s own projects, notably the team working on Bing Maps.
TypeScript is open-source, and the code is written in TypeScript itself. You can check out the code on GitHub.
What is static type checking and how does TypeScript implement it?
JavaScript is dynamically typed. Therefore, programs written in JavaScript do not know the data type of a variable until that variable is assigned a value at runtime. The variable can be reassigned or coerced into a value of a different type with no issues or warning. This can result in bugs that are often overlooked, especially in large applications.
TypeScript, on the other hand, uses static typing. Variables can be given a type when they are declared. TypeScript will check types at compile time, and throw an error if the variable is ever given a value of a different type. However, the error does not prevent the code from executing. The code will still be compiled into plain JavaScript and run normally. In this way, TypeScript is kind of like a “spellcheck” for your code. It will let you know when something looks off, but it won’t change how your code runs.
Static typing is optional in TypeScript. Variables can be given the type any , which will allow its values to be any type. If no type is given, the type will be set to any by default.
Assigning types in TypeScript
Below, we assign the type string to the parameter of a function.
If we call askForFood(11) , we will receive this error at compile time: Argument of type ‘11’ is not assignable to parameter of type ‘string’. However, the JavaScript file will still be created, and when ran, the following will log to the console: May I please have 11?
TypeScript will also inform you if a function has been called with an unexpected number of arguments. If we call askForFood() , we will receive the error: Expected 1 arguments, but got 0. When ran, the JavaScript program will still log the following: May I please have undefined?
Using interfaces to describe objects with properties
We can use interfaces to give types to object properties. We use the interface when creating objects that should have properties matching the ones we described in the interface.
When compiling the above code, we would see the error: Types of property ‘graduationYear’ are incompatible. Type ‘string’ is not assignable to type ‘number’.
Defining classes
It wasn’t until the introduction of ECMAScript2015, or ES6, that JavaScript introduced classes to the language. However, it is important to note that these classes do not change the language’s prototype-based inheritance.
TypeScript allowed for the ability to use classes before they were officially implemented in ES6. TypeScript allows the developer to extend existing classes to construct new ones using inheritance.
Because Tiger inherits methods from the base class Feline , when we create an instance of Tiger , the instance tiger has both the method catchMice() and rawr() .
What else can TypeScript do?
In addition to displaying the errors at compile time, certain IDEs such as Visual Studio Code will present the errors to the developer while they are typing the code. This makes correcting simple careless errors much quicker and easier.
TypeScript can also infer types that aren’t explicitly declared by the developer, such as inferring the return value type of a function. If the function is adding two parameters that were declared as both number , TypeScript will infer the return value must be of type number .
Furthermore, TypeScript offers more advanced functionality than the simple examples offered in this blog post. You can visit the language’s documentation for the most up-to-date features and how to use them.
Who’s using TypeScript?
Teams at AngularJS, Ionic, NativeScript, Aurelia, SitePen, and Epic are all using TypeScript to make their code more manageable, improve their development workflow, and assist in the debugging process.
If you are using JavaScript to write large programs, or you often find yourself consistently finding bugs due to mismatched types, you may wish to give TypeScript a try.
Источник
Вводный курс по TypeScript
TypeScript — это расширенная версия JavaScript, главной целью которого является упрощение разработки крупных JS-приложений. Этот язык добавляет много новых принципов — классы, дженерики, интерфейсы, статические типы, что позволяет разработчикам использовать разные инструменты, такие как статический анализатор или рефакторинг кода.
Стоит ли использовать TypeScript?
В первую очередь возникает вопрос: а какие преимущества у этого языка?
- Статическая типизация. JavaScript — это язык с динамической типизацией, то есть компилятор не знает, что за тип переменной вы используете, пока эта переменная не будет инициализирована. Подобные вещи могут вызвать трудности и ошибки в ваших проектах. В TypeScript появляется поддержка статической типизации, что при грамотном использовании исключает ошибки, связанные с ошибочной типизацией переменной. При этом динамическая типизация вовсе не пропадает, и ей можно пользоваться.
- Лучшая поддержка в IDE. Основным преимуществом языка TypeScript перед JavaScript является лучшая поддержка со стороны IDE, что включает Intellisense, информацию компилятора в реальном времени, отладку и многое другое. Также существуют различные расширения, которые помогают в процессе разработки.
- Доступ к новым возможностям ECMAScript. В TypeScript есть поддержка новых возможностей ECMAScript, поэтому можно разрабатывать приложения с помощью новейших инструментов, не волнуясь о поддержке их браузером.
В каких случаях стоит использовать TypeScript?
Хоть выше были приведены достаточные аргументы к использованию этого языка, TypeScript не является универсальным решением. В каких же случаях лучше всего подходит этот язык?
- В случае крупного приложения. TypeScript отлично подойдёт, если ваше приложение имеет большую архитектуру и кучу кода, а особенно если над этим приложением работают несколько разработчиков.
- В случае, когда вы и ваша команда знакомы с ЯП со статической типизацией. Команде стоит смотреть в сторону TypeScript, когда они хотят разрабатывать приложение на JavaScript и уже знакомы с Java или C#, ведь те являются языками со статической типизацией.
Установка TypeScript
Установить TypeScript совсем не сложно — достаточно загрузить его через пакетный менеджер npm и создать TypeScript-файл:
npm install -g typescript
После его установки можно сразу перейти к рассмотрению возможностей этого языка и его синтаксиса.
Типы переменных
Number
Все числовые переменные в TypeScript существуют в виде числа с плавающей запятой. Числовой тип получают даже двоичные и шестнадцатеричные числа:
String
Как и другие языки, TypeScript использует тип String для хранения текстовой информации:
Можно создавать и многострочные переменные, а также в строки можно вставлять выражения, если выделить строку символами « :
Boolean
Куда же без одного из основных типов данных:
Присвоение типов
Основной способ присвоения типа переменной — написание его после самого имени переменной через символ : .
Одиночный тип переменной
Простой пример, где присваивается значение переменной типа String :
Такой способ действителен для всех типов данных.
Мультитип переменной
Переменной можно присваивать несколько типов, перечисляя их через оператор | .
В коде выше переменной назначается два типа: строчный и численный. Теперь переменной можно присваивать как текстовые данные, так и числовые.
Проверка типов
Ниже будут описаны два основных (на деле их существует больше) способа проверки типа переменной.
Typeof
Команда typeof работает только с базовыми типами данных. Это означает, что эта команда может определить только типы, описанные выше.
В коде выше создаётся переменная типа String , а потом проверяется, является ли эта переменная числом (что, естественно, всегда будет возвращать false ).
Instanceof
Это оператор, который работает почти так же, как typeof . Отличие только в том, что это оператор может определять не только базовые типы, но и собственные.
В коде выше создаётся собственный тип, а потом инициализируется переменная этого типа. Далее этот тип переменной сравнивается с типом Human , что, в данном случае, возвращает true .
Тип Assertions
Иногда приходится преобразовывать (кастовать) переменную одного типа в другой тип. Особенно часто это случается, когда переменную типа any (или другого произвольного типа) нужно передать в функцию, которая принимается аргумент определённого типа.
Существует много решений этой задачи, но ниже будут описано два самых популярных из них.
Ключевое слово as
Чтобы кастовать переменную, нужно после оператора as написать тип, в который переводится переменная.
В этом коде текстовая переменная str кастуется в тип String , а поэтому можно использовать параметр length (это сработает и без кастования, если есть соответствующее разрешение в настройках TSLINT).
Оператор <>
Выполняет абсолютно такую же работу, что и ключевое слово as .
Этот код работает идентично предыдущему — разница только синтаксическая.
Источник