1645619460
Erfahren Sie, wie Sie Funktionen in TypeScript verwenden. Erfahren Sie, wie Sie Typen für Parameter und Rückgabetypen definieren, wie Sie Funktionstypen erstellen und vieles mehr.
Funktionen sind grundlegender Bestandteil von JavaScript. Sie helfen dabei, Code wiederverwendbar zu machen und gleichzeitig flexibel zu bleiben. TypeScript erweitert diese Vorteile, indem es Ihnen hilft, typsichere Funktionen zu schreiben. Dieses Tutorial zeigt Ihnen, wie Sie Funktionen in TypeScript verwenden, wie Sie Typen für Parameter, Rückgabetypen und mehr angeben.
Funktionen gehören zu den am häufigsten verwendeten Sprachmerkmalen. Das gilt nicht nur für JavaScript und TypeScript, sondern auch für andere Programmiersprachen. In JavaScript gibt es jedoch ein Problem. JavaScript ist keine Programmiersprache vom statischen Typ. Aus diesem Grund gibt es einige Dinge, die Sie nicht tun können.
Wenn Sie beispielsweise eine Funktion definieren, können Sie keine zulässigen Typen für ihre Parameter angeben. Dadurch wird es einfacher, eine Funktion mit Argumenten eines falschen Typs aufzurufen. Sie können eine Funktion erstellen, die zwei Zahlen als Parameter akzeptiert und sie aufrufen, indem Sie zwei Zeichenfolgen als Argumente übergeben. JavaScript wird Sie nicht aufhalten.
Sie können auch nicht den Rückgabetyp einer Funktion angeben. Dies kann zu Problemen führen, wenn ein Teil des Programms, der eine Funktion aufruft, etwas erwartet, während die Funktion etwas anderes zurückgibt. Hier kann TypeScript hilfreich sein. Es stimmt, dass TypeScript den Funktionen nicht wirklich etwas Neues hinzufügt.
Funktionen in TypeScript sind immer noch Funktionen, also Funktionen, die Sie aus JavaScript kennen. TypeScript macht Funktionen sicherer und vorhersehbarer. Dies geschieht durch die Kombination von Funktionen mit seinem leistungsstarken Typensystem. Dadurch können Sie sicherstellen, dass Ihre Funktionen die richtigen Typen empfangen und zurückgeben. Schauen wir uns an, wie.
Wenn Sie eine Funktion erstellen, können Sie auch alle Parameter angeben, die sie akzeptiert. Dadurch wird Ihr Code flexibler und lässt sich unter verschiedenen Bedingungen leichter wiederverwenden. Mit TypeScript können Sie auch Typen für diese Parameter angeben. Wenn Sie versuchen, eine Funktion mit einem Argument eines falschen Typs aufzurufen, werden Sie von TypeScript gewarnt.
Die Syntax zum Definieren von Typen für Funktionsparameter ist einfach. Er setzt sich aus Doppelpunkt ( :
) und dem Typ zusammen. Zuerst definieren Sie einen Parameter. Dann fügen Sie direkt danach einen Doppelpunkt hinzu. Danach geben Sie an, welcher Typ für diesen bestimmten Parameter zulässig ist.
// Create a function that accepts two parameters: str1 and str2.
// Both parameters must be of type string.
function joinStrings(str1: string, str2: string) {
return str1 + str2
}
// This will work:
joinStrings('Wo', 'rld')
// Output:
// 'World'
// This will not work:
joinStrings('Hel', 135)
// TS error: Argument of type 'number' is not assignable to parameter of type 'string'.
Mit TypeScript können Sie auch mehrere Typen angeben. Sie können dies erreichen, indem Sie Union-Typen verwenden . Das bedeutet im Grunde, dass Sie zwei oder mehr Typen nehmen und TypeScript mitteilen können, dass jeder dieser Typen verwendet werden kann. Wenn Sie Vereinigungstypen verwenden möchten, geben Sie alle möglichen Typen an und verwenden Sie |
, um sie zu trennen.
// Create a function that accepts one parameter.
// This parameter can be either number, string or boolean.
function numStrBool(val: number | string | boolean) {
return typeof val
}
// This will work in TypeScript:
numStrBool(15)
// Output:
// 'number'
// This will also work in TypeScript:
numStrBool('Tea')
// Output:
// 'string'
// This will also work in TypeScript:
numStrBool(true)
// Output:
// 'boolean'
// This will not work in TypeScript:
numStrBool({ key: 15 })
// TS error: Argument of type '{ key: number; }' is not assignable to parameter of type 'string | number | boolean'.
Genau wie in JavaScript können Sie auch in TypeScript einige Parameter als optional markieren. Die Syntax ist dieselbe. ?
Um einen Parameter als optional zu markieren, fügen Sie direkt dahinter ein Fragezeichen ( ) ein. Wenn Sie mit Funktionen in TypeScript arbeiten, steht das Fragezeichen nach dem Parameternamen und vor dem Doppelpunkt und dem Typ.
// Create a function that accepts two parameters,
// the first one required and the second optional:
function combineWords(word1: string, word2?: string) {
return `${word1}${word2 ? word2 : ''}`
}
// This will work in TypeScript:
combineWords('Hello', 'world')
// Output:
// 'Helloworld'
// This will also work in TypeScript:
combineWords('Say', 'Bye')
// Output:
// 'SayBye'
// This will also work in TypeScript:
combineWords('Hi')
// Output:
// 'Hi'
// This will not work in TypeScript:
combineWords()
// TS error: Expected 1-2 arguments, but got 0.
Mit TypeScript können Sie auch Standardwerte für Funktionsparameter definieren. Das ist nicht alles. Wenn Sie Standardwerte für Funktionen in TypeScript definieren, müssen Sie Typen für diese Parameter nicht explizit angeben. TypeScript kann Standardwerte verwenden, um Typen für Parameter automatisch abzuleiten. Weniger Arbeit für Sie.
Die Syntax für Standardwerte ist dieselbe wie in JavaScript . Sie geben einen Parameter an und fügen direkt danach ein Gleichheitszeichen mit dem Standardwert hinzu. Wenn Sie auch explizit einen Typ für den Parameter angeben möchten, geben Sie zuerst den Typ an. Dies bedeutet, dass die folgende Reihenfolge verwendet wird: Parametername, Doppelpunkt und Typ, Gleichheitszeichen und Standardwert.
// Example 1: default parameters and implicit type:
// Create a function that accepts two parameters.
// Both parameters are of type numbers,
// the second has default value 0.
function addTwoNumbers(num1: number, num2 = 0) {
return num1 + num2
}
// TS will add type for num2 implicitly:
// addTwoNumbers(num1: number, num2: number = 0)
// This will work in TypeScript:
addTwoNumbers(98, 656)
// Output:
// 754
// This will also work in TypeScript:
addTwoNumbers(63)
// Output:
// 63
// This will not work in TypeScript:
addTwoNumbers('13')
// TS error: Argument of type 'string' is not assignable to parameter of type 'number'.
// Example 2: default parameters and explicit type:
function addTwoNumbers(num1: number, num2: number = 0) {
return num1 + num2
}
Einige Funktionen können eine beliebige Anzahl von Argumenten akzeptieren. Hier ist die Syntax der Restparameter sehr nützlich. In TypeScript können Sie Typ für rest-Parameter genauso einfach angeben wie alle anderen Parameter. Die Syntax ist dieselbe. Sie fügen den rest-Parameter hinzu und folgen ihm mit einem Doppelpunkt und dem Typ.
Wenn Sie mit Ruheparametern arbeiten, denken Sie an eines. Parameter, die als Restparameter übergeben werden, werden in einem Array gesammelt. Das bedeutet, dass Sie auch den Array-Typ verwenden müssen, entweder type[]
oder Array<type>
.
// Create a function that accepts two parameters.
// The first parameter is a string.
// The second is a rest parameter and is an array of strings.
function buildATeam(leader: string, ...teammates: string[]) {
return `Team is composed of ${leader} as a the team leader and ${teammates.length > 0 ? teammates.join(', ') : 'nobody'} as the core team.`
}
// This will work in TypeScript:
buildATeam('Joe', 'Vicky', 'Thomas')
// Output:
// 'Team is composed of Joe as a the team leader and Vicky, Thomas as the core team.'
// This will also work in TypeScript:
buildATeam('Sandra', 'Alex', 'Jack', 'Victor')
// Output:
// 'Team is composed of Sandra as a the team leader and Alex, Jack, Victor as the core team.'
// This will also work in TypeScript:
buildATeam('Stuart')
// Output:
// 'Team is composed of Stuart as a the team leader and nobody as the core team.'
// This will not work in TypeScript:
buildATeam(13, 15)
// TS error: Argument of type 'number' is not assignable to parameter of type 'string'.
Mit TypeScript können Sie auch den Rückgabetyp einer Funktion angeben. Das heißt, Sie werden dies nicht sehr oft tun. In den meisten Fällen kann TypeScript den Rückgabetyp der Funktion basierend auf Rückgabeanweisungen innerhalb der Funktion selbst ableiten. Sie müssen diese Typen nicht explizit angeben.
Was ist, wenn TypeScript den Rückgabetyp nicht ableiten kann oder Sie ihn selbst angeben möchten? Um den Rückgabetyp der Funktion anzugeben, müssen Sie einen Doppelpunkt und den Typ direkt nach der Parameterliste vor dem Funktionsrumpf hinzufügen.
// Create a function that accepts two parameters.
// Both parameters are numbers.
// Set the return type to be a number (the '): number {' part).
function numToPow(num: number, exp: number): number {
return num ** exp
}
// This will work in TypeScript:
numToPow(15, 8)
// Output:
// 2562890625
// This will not work in TypeScript:
numToPow(12, '9')
// TS error: Argument of type 'string' is not assignable to parameter of type 'number'.
Wenn Sie mit Funktionen in TypeScript arbeiten, definieren Sie normalerweise alle ihre Typen, wenn Sie eine Funktion deklarieren. Was TypeScript auch ermöglicht, ist das Definieren einer Funktionssignatur, bevor Sie die eigentliche Funktion erstellen. Später, wenn Sie die Funktion erstellen, verwendet TypeScript die Signatur, um alle Typen automatisch für Sie abzuleiten.
Diese Signatur wird als Funktionstyp bezeichnet. Dies kann nützlich sein, wenn Sie eine bestimmte Funktionssignatur erwarten. Dieser Funktionstyp besteht aus zwei Teilen: Parameter und Rückgabetyp. Wenn Sie einen Funktionstyp deklarieren, müssen Sie diese beiden Teile angeben.
// Create function type for function subtract.
// This function accepts two parameters, both are numbers.
// Its return type is also a number.
let subtract: (a: number, b: number) => number
// Assign the actual function to the variable:
subtract = function (a, b) {
return a - b
}
// This will not work in TypeScript:
subtract = function (a: string, b: string) {
return a + b
}
// TS error: Type '(a: string, b: string) => string' is not assignable to type '(a: number, b: number) => number'.
Denken Sie daran, dass Sie beim Deklarieren des Funktionstyps die Typen nicht erneut angeben müssen, wenn Sie die eigentliche Funktion zuweisen. TypeScript leitet alle Typen implizit basierend auf dem zuvor erstellten Funktionstyp ab.
// Create function type for function subtract:
let subtract: (a: number, b: number) => number
// These types are redundant:
subtract = function (a: number, b: number) {
return a - b
}
Es gibt einen anderen Weg, dies zu erreichen. Sie können einen Funktionstyp auch während der Funktionszuordnung anlegen. Dadurch können Sie beide Schritte zu einem kombinieren.
// Create function with function:
let subtract: (a: number, b: number) => number = function (a: number, b: number) {
return a - b
}
Die gerade besprochenen Methoden zum Erstellen von Funktionstypen haben einen Nachteil. Sie sind nicht wirklich wiederverwendbar. Sie erstellen einen Funktionstyp, weisen ihm eine Funktion zu und fertig. Sie können diesen Typ nicht erneut für eine andere Funktion verwenden, es sei denn, Sie kopieren den Code. Zum Glück gibt es einen anderen Weg, eigentlich zwei.
Sie können auch Funktionstypen mit Typen und Schnittstellen erstellen . Der Vorteil beider ist die bereits erwähnte Wiederverwendbarkeit. Typ und Schnittstelle werden nicht aufhören zu existieren, nachdem Sie sie verwendet haben. Wenn Sie einen Funktionstyp mit einem Typ oder einer Schnittstelle erstellen, können Sie ihn verwenden, wann immer Sie wollen und so oft Sie wollen.
Die Syntax für type zum Deklarieren eines Funktionstyps ist der Syntax, die Sie oben gesehen haben, sehr ähnlich. Es gibt nur zwei Unterschiede. Zuerst ersetzen Sie die Variable Schlüsselwort durch type
Schlüsselwort. Zweitens ersetzen Sie den Doppelpunkt nach dem Variablennamen durch ein Gleichheitszeichen. Sie erstellen im Grunde einen neuen Typ und weisen ihm eine Funktionssignatur zu.
Wenn Sie Ihren neuen Typ verwenden möchten, verwenden Sie ihn zusammen mit Doppelpunkten, wenn Sie einen neuen Funktionsausdruck erstellen .
// Function type with variable:
let subtract: (a: number, b: number) => number
// Function type with type:
type TakeNumsReturnNums = (a: number, b: number) => number
// Use the "TakeNumsReturnNums" type with function expression:
const subtract: TakeNumsReturnNums = (a, b) => a - b
// This will work in TypeScript:
subtract(97, 13)
// Output:
// 84
// This will not work in TypeScript:
subtract(55, '15')
// TS error: Argument of type 'string' is not assignable to parameter of type 'number'.
// Use the type again:
const sumNumbers: TakeNumsReturnNums = (x, y) => x + y
// And again:
const divideNumbers: TakeNumsReturnNums = (c, d) => c / d
Das Gleiche mit einer Schnittstelle zu tun, erfordert eine andere Syntax. Sie erstellen eine neue Schnittstelle. Darin geben Sie die Typen für die Parameterliste als Schlüssel und den Rückgabetyp als Wert an. Dann verwenden Sie es auf die gleiche Weise wie den Typ.
// Create interface for subtract function:
interface TakeNumsReturnNums {
// Syntax:
// (types for parameter list): return type;
(a: number, b: number): number;
}
// Use the "TakeNumsReturnNums" interface with function expression:
const subtract: TakeNumsReturnNums = (a, b) => a - b
// This will work in TypeScript:
subtract(55, 21)
// Output:
// 34
// This will not work in TypeScript:
subtract(true, 66)
// TS error: Argument of type 'boolean' is not assignable to parameter of type 'number'.
// Use the type again:
const sumNumbers: TakeNumsReturnNums = (x, y) => x + y
// And again:
const divideNumbers: TakeNumsReturnNums = (c, d) => c / d
TypeScript erleichtert das Schreiben von Funktionen, die typsicher und vorhersehbarer sind. Ich hoffe, dass dieses Tutorial Ihnen geholfen hat, die Verwendung von Funktionen in TypeScript zu verstehen. Wie man Typen für Parameter und Rückgabetypen definiert und wie man Funktionstypen erstellt.
1654588030
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 🌹
If you are here to read the book online get started.
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.
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.
All the amazing contributors 🌹
Share URL: https://basarat.gitbook.io/typescript/
Author: Basarat
Source Code: https://github.com/basarat/typescript-book/
License: View license
1601549700
Today I am going to talk about new features in Typescript 4.0.
TypeScript 4.0 comes with lots of new features to make JavaScript development easier.
You can label tuple elements.
You can write:
type Range = [start: number, end: number];
to restrict args
to have a string and a number.
you can also write:
type Foo = [first: number, second?: string, ...rest: any[]];
to have rest entries in your tuple.
If your tuple has type Foo
, then the tuple starts with a number and a string.
Then the rest of the entries can be anything.
Labels don’t require you to name your variables differently when destructuring.
For example, if you have:
function foo(x: [first: string, second: number]) {
const [a, b] = x;
}
then you can name the destructured variables anything you want.
#software-development #typescript-with-react #typescript #typescript-4 #react native
1599308024
icrosoft recently announced the availability of TypeScript version 4.0. The developers at the tech giant claimed that this version of the language represents the next generation of TypeScript with more expressivity, productivity as well as scalability.
Developed by the tech giant, TypeScript is an open-source programming language that is built on top of JavaScript by adding syntax for static type definitions. The types in this language provide a way to describe the shape of an object, providing better documentation as well as allowing TypeScript to validate that the code is working correctly.
According to the latest Stack Overflow Developers survey 2020, it secured the second position as the most loved language and 9th position among 25 programming languages as the most commonly used programming language by the developers. In one of our articles, we discussed how TypeScript weighs over other programming languages.
It is one of the fastest-growing programming languages among the developers. The motive behind this language is that while writing down the types of values and where they are used, developers can use TypeScript to type-check the code and let them know about mistakes before they run the code. TypeScript compiler can be used to strip away types from the code, leaving them with clean, readable JavaScript that runs anywhere.
In the present scenario, TypeScript is a core part of many developer’s JavaScript stack. The language adds optional types to JavaScript that support tools for large-scale JavaScript applications for any browser, for any host and on any operating systems.
The program manager of TypeScript, Daniel Rosenwasser, said in a blog post, “In our past two major versions, we looked back at some highlights that shined over the years. For TypeScript 4.0, we’re going to keep up that tradition.”
Based on the feedback by the developer’s community, TypeScript 4.0 includes many intuitive features that are focussed on boosting the performance of this language. Some of them are mentioned below-
According to Rosenwasser, previously, compiling a program after a previous compile with errors under incremental would result in extremely slow performance when using the –noEmitOnError flag. The reason is, none of the information from the last compilation would be cached in a .tsbuildinfo file based on the –noEmitOnError flag.
But now TypeScript 4.0 changes this. The new update provides a great speed boost in these scenarios, and in turn, improves the build mode scenarios, which imply both –incremental and –noEmitOnError.
#developers corner #microsoft #microsoft releases typescript 4.0 #programming language #programming language with high salary #typescript #typescript 4.0
1603953021
Maybe you’ve been using JavaScript for a while and you’ve been hearing the buzz around… TypeScript. In this 2 part series, we’ll take a look at Why TypeScript? and Why Not TypeScript?
According to the TypeScript website “TypeScript extends JavaScript by adding Types… TypeScript code is transformed into JavaScript code via the TypeScript compiler or Babel. This JavaScript is clean, simple code which runs anywhere JavaScript runs…”. In short, many refer to TypeScript as a superset of JavaScript.
In my opinion, this is kind of true and kind of not. Technically, not all valid JavaScript code can also be TypeScript code. We’ll talk about that later on. But, at its core, TypeScript was designed to allow developers to turn JavaScript, a dynamic programming language (one that is interpreted at runtime) into a statically typed programming language (one that is compiled before running). Let’s dive in.
TypeScript makes use of features similar to languages like C## or Java: it truly is object oriented. This allows for more robust code. It enables the developer to implement type checking and make use of interfaces, classes, inheritance, etc. This can up the game as far as clean code when looking at a JavaScript program and a TypeScript program.
_Why did you throw in the word _potentially? Well, most valid JavaScript code can become TypeScript code. This means you don’t have to use the object oriented or typed features of TypeScript. Remember, TypeScript is optionally typed. It is not required. If TypeScript is utilized merely like JavaScript then improved code quality may not actually be a thing.
#typescript #programming #javascript #web-development #developer
1645955100
One of the most requested demos on this channel has been #TypeScript template literal types. So I this lesson I will break down how this feature works in TypeScript and some real world use cases 🌹
Github: https://github.com/basarat/demo-template-literal
Chapters:
0:00 Why
0:17 Template Literal Types
2:25 Example Use Cases
4:45 Final Thoughts