Typescript의 고급 개념 이해
JavaScript를 사용할 때 많은 개발자들이 디버깅의 번거로움을 알고 있습니다.프로그램을 실행합니다.새로운 오류를 찾았습니다.씻고 반복.몇 시간의 디버깅을 거쳐 당신은 마침내 문제를 해결하였다.JavaScript처럼 컴파일할 수 없는 프로그래밍 언어에 대한 일반적인 질문입니다.
Microsoft는 JavaScript의 단점을 해결하기 위해 TypeScript를 만들었습니다.대형 팀이 TypeScript를 기술 스택에 적용하는 장점을 인식하면서 점점 더 많은 개발자들이 이를 알아야 한다.
오늘 당신은 타자 스크립트의 고급 개념을 배워서 전문가가 될 수 있습니다.
당신은 다음과 같이 공부할 것입니다.
타자 스크립트는 무엇입니까?
Microsoft에서 작성 및 유지 보수한 TypeScript은 JavaScript의 하이퍼집합으로, 모든 기능성 JavaScript 코드가 TypeScript에서 유효하다는 것을 의미합니다.이 언어는 응용 프로그램 크기 개발을 위한 JavaScript로 이해할 수 있으며 주로 두 가지 측면에 주목한다.
TypeScript의 구성 요소는 일반적으로 언어 자체로 본질적으로 자바스크립트에 다른 특성과 문법을 더하고 코드를 자바스크립트로 변환하는 컴파일러이며 언어 서비스로 컴파일러 파이프의 끝에 편집기와 유사한 프로그램을 제공한다.
그렇다면 왜 타자 스크립트를 사용해야 합니까?
타자 스크립트 설치
TypeScript를 자세히 검토하기 전에 TypeScript를 성공적으로 설치했는지 확인하십시오.TypeScript 도구를 가져오는 두 가지 주요 방법은 npm 노드를 통과하는 것입니다.또는 TypeScript의 비주얼 스튜디오 플러그인을 설치합니다.
NPM:
설치하다.
> npm install -g typescript
Compile
> tsc helloworld.ts
If you aren't using NPM, you can download TypeScript through this link.
TypeScript의 장점과 한계
타이핑
JavaScript is a dynamically typed language, meaning that type errors are found only during runtime. This can be a significant downside for large teams working on complex projects, as finding all mistakes to the code beforehand would be significantly easier.
TypeScript offers optional static typing so that a variable can't change its types and can only accept certain values. This typing helps the TypeScript compiler find more bugs so that developers are working with less error-prone code. Type guards create more structure for the code by making it more readable, and more easily refactored.
Interested in learning about more differences between JavaScript and TypeScript? You can learn more here: What's the difference between JavaScript and TypeScript?
IDE 지원
Because TypeScript offers types, text editors and integrated development environments (IDE) can provide more helpful information to developers. These environments can offer auto-completion, code navigation, error flagging and more to increase the productivity of teams.
Some popular environments that support TypeScript 3:
Microsoft Visual Studio
WebStorm
Visual Studio Code
Atom
Eclipse
브라우저 호환성
Browser compatibility is one of the powerful features that TypeScript offers. The TypeScript compiler transforms your code to make it compatible with all the modern browsers. This compatibility is because the compiler is able to translate the TypeScript code into vanilla JS, which all devices, platforms, and browser support.
Though there are many advantages to using TypeScript, it's not a perfect solution. One downside to improving your code readability is that you have to write more code, which can potentially increase your development time. It also increases the size of your TypeScript files compared to using vanilla JavaScript.
타자 스크립트 개발자가 되다.
Educative's Learn TypeScript course allows complete beginners to learn the primary concepts to become a full-fledged TypeScript developer.
Learn TypeScript: The Complete Course for Beginners
타자 배웠어요?
Tackle the advanced concepts and improve your TS skills with hands-on practice.
엄격한 유형 소개
Now that we have a sense of what TypeScript has to offer, let's dive into some of the more advanced concepts that make TypeScript a powerful tool.
mplicitany 없음
According to the documentation, the definition of noImplicitAny
is to "raise errors on expressions and declarations with any implied any type."
This means that whenever TypeScript can infer a type, you will get an error if you allow noImplicitAny
. This example can be seen by passing function arguments.
function print(arg) {
send(arg);
}
print("hello");
print(4);
위 코드에서 print
함수의 유효한 매개 변수는 무엇입니까?함수 매개 변수에 유형을 추가하지 않으면 TypeScript에서 any
유형의 매개 변수를 지정하여 유형 확인을 닫습니다.코드 보안을 좋아하는 개발자들은
noImplicityAny
을 사용할 수 있으며 코드의 any
유형에 대한 어떠한 가능성도 알려준다.같은 print
함수에 무슨 일이 일어날지 봅시다.function print(arg) { // Error : someArg has an implicit `any` type
send(arg);
}
오류를 수정하려면 함수 매개 변수에 주석을 달 수 있습니다.function print(arg: number) { // Error : someArg has an implicit `any` type
send(arg);
}
그러나 여전히 any
을 입력해야 한다면 파라미터를 any
으로 명시적으로 표시할 수 있다.function print(arg: any) { // Error : someArg has an implicit `any` type
send(arg);
}
알 수 없었어
unknown
유형은 any
유형과 유사하다. 모든 유형은 any
과 unknown
유형에 분배할 수 있지만 any
유형은 다른 유형에 분배할 수 있지만 unknown
유형은 다른 유형에 분배할 수 없다.차이는 사람을 곤혹스럽게 하는 개념일 수 있으니 예를 들어 보자.function example1(arg: any) {
const a: str = arg; // no error
const b: num = arg; // no error
}
function example2(arg: unknown) {
const a: str = arg; // 🔴 Type 'unknown' is not assignable to type 'string'.(2322)
const b: num = arg; // 🔴 Type 'unknown' is not assignable to type 'number'.(2322)
}
변수 arg
은 두 함수에 전달되고 이 두 함수의 유형은 string
, number
또는 다른 유형일 수 있다.유형에 상관없이 arg
은 any
과 unknown
유형으로 지정된다.그러나
any
유형과 달리 unknown
유형의 변수는 다른 유형에 분배할 수 없다. 예를 들어 7행과 8행과 같다.any
유형은 양방향이고 unknown
유형은 단방향이다.함수에 전달할 값의 유형을 모르지만
unknown
에서 벗어나기를 원한다면 any
유형이 도움이 될 수 있습니다.이것은 코드의 안전성을 증가시켰다. 왜냐하면 any
유형이 전파될 수 있기 때문에 코드 라이브러리에 오류가 발생하기 쉽다.엄격한 수표
TypeScript에서는
null
과 undefined
을 각 유형에 할당할 수 있으며 이는 모든 유형의 도메인에 있음을 의미합니다.let num: number = 123;
num = null; // Okay
num = undefined; // Okay
값이 null
또는 undefined
인 변수를 호출할 수 있기 때문에 의외의 오류가 발생할 수 있습니다.interface Person {
hello(): void;
}
const num: number = undefined;
const str: string = null;
const person: Person = null;
person.hello(); // 🔴 Runtime Error!
엄격한 공중 검사 모드에서 null
과 undefined
은 자동으로 모든 유형에 속하지 않기 때문에 null
또는 undefined
을 포함하지 않는 유형에 사용할 수 없다.이렇게 하면, 컴파일할 때 오류, 즉 Object is possibly 'undefined'
을 얻을 수 있습니다.Luna
은 Dog
의 실례 대상이다.class Dog
{
age: number
breed: string
constructor(age: number, breed: string)
{
this.age = age
this.breed = string
}
getRelativeAge(): number
{
return this.age * 7
}
}
let Luna = new Dog(2, 'Labrador')
이 구문은 JavaScript ES5에서 함수 객체를 사용하는 것과 같습니다.function Dog(age, breed)
{
this.age = age
this.breed = breed
}
Dog.prototype.getRelativeAge = function() {
return this.age * 7
}
var Spot = new Dog(2, 'Labrador')
상속권
객체를 작성하는 방법을 알게 된 이상 TypeScript의 상속을 이해하는 것이 중요합니다.상속은 하위 클래스가 부모 클래스로부터 일부 속성을 상속할 수 있도록 합니다.
예를 들어, 상위
Animal
이 있습니다.class Animal
{
age: number
breed: string
constructor(age: number, breed: string)
{
this.age = age
this.breed = breed
}
makeSound_(sound: string): void
{
console.log(sound)
console.log(sound)
console.log(sound)
}
}
그리고 Dog
하위 클래스를 만들 수 있습니다.super
키워드를 사용하여 기본 계승을 실현할 수 있으며 이 키워드는 하위 클래스에서 상응하는 부 함수를 호출하는 함수로 사용된다.class Dog extends Animal
{
playsFetch: boolean constructor(age: number, breed: string, playsFetch: boolean)
{
super(age, breed) // call parent constructor
this.playsFetch = playsFetch
} makeSound(): void
{
super.makeSound_('woof woof')
} getAgeInHumanYears(): number
{
return this.age * 7 // super.age will throw error
}
}
class Cat extends Animal
{
constructor(age: number, breed: string)
{
super(age, breed)
} makeSound(): void
{
super.makeSound_('meow meow')
}
}
이음매
JavaScript(및 TypeScript)의 인터페이스 기능은 런타임에 영향을 주지 않으므로 강력합니다.TypeScript는 변수의 구조를 설명할 수 있도록 해 줍니다. 이것은 당신에게 더 많은 권한을 줍니다.
interface Point {
x: number; y: number;
}
declare var test: Point;
TypeScript의 인터페이스는 개방적이기 때문에 다른 작성자는 test
변수의 기존 성명을 바탕으로 구축할 수 있다.interface Point {
x: number; y: number;
}
declare var myPoint: Point;
interface Point {
z: number;
}
var myPoint.z; // Allowed
클래스는 implements
키워드를 사용하여 미리 정의된 대상 구조를 따를 수 있도록 인터페이스를 실현할 수 있다.interface Point {
x: number; y: number;
}
class MyPoint implements Point {
x: number; y: number; // Same as Point
}
이 implements
키워드는 인터페이스의 모든 변경 사항에 컴파일 오류가 발생하기 때문에 코드 라이브러리를 쉽게 업데이트할 수 있습니다.interface Point {
x: number; y: number;
z: number; // New member
}
class MyPoint implements Point { // ERROR : missing member `z`
x: number; y: number;
}
타자 스크립트의 유형
TypeScript의 가장 중요한 부분은 기존 범주 유형에서 사용자 정의 유형을 만드는 것입니다.
연합형
일반적으로, 코드가 여러 종류의 데이터 형식을 허용하기를 원할 수도 있습니다.
null
또는 undefined
의 값을 받아들일 때 이런 수요는 특히 진실하다.union 유형은 이 문제를 해결할 수 있습니다. |
의 주석으로 표시됩니다.const hello = (name: string | undefined) => { /* ... */ };
이 예에서 name
유형은 string | undefined
으로 정의되었는데 이것은 name
유형의 모든 변수가 string
또는 undefined
일 수 있음을 의미한다.교차점 유형
교차점 유형은 여러 유형을 하나로 조합하여 새로운 유형이 조합 유형의 특징을 가지도록 한다.다음과 같이
extend
키워드를 사용하여 이 작업을 수행할 수 있습니다.function extend<T, U>(first: T, second: U): T & U {
return { ...first, ...second };
}
const x = extend({ a: "hello" }, { b: 42 });
// x now has both `a` and `b`
const a = x.a;
const b = x.b;
모듈 유형
JavaScript와 달리 TypeScript는 Tuple types을 제공하며, 비통일 형식과 고정된 수량의 요소를 사용하여 그룹을 표시할 수 있습니다.아래의 예는 하나의 원조를 보여 준다.
var nameNumber: [string, number];
// Okay
nameNumber = ['Ben', 12345];
// Error
nameNumber = ['Ben', '12345'];
기타 공부할 이야기
진정한 타자 고수가 되려면 아직도 배워야 할 것이 많다.이 목록을 보고 미래에 무슨 일이 일어날지 봅시다.
포장 및 리소스
이제 TypeScript에서 더 높은 주제를 알게 되었으니 더 강력한 TypeScript 기능을 탐색할 때가 되었습니다.언어를 파악하고 TypeScript에서 제공하는 도구를 활용할 수 있도록 Advanced TypeScript Masterclass을 살펴보십시오.
본 과정을 마치면 자신의 유형 스크립트 기술에 대해 자신감을 가지게 되고 자신의 유형을 작성할 수 있으며 컴파일한 후에 오류를 쉽게 식별할 수 있으며 전체적인 자바스크립트 지식도 향상시킬 수 있습니다.관련된 주제는 엄격한 유형, 범용 함수, 범용 인터페이스, 조합 유형, 흔한 오류 등을 포함한다.
TypeScript에 대한 기사 계속 보기
Reference
이 문제에 관하여(Typescript의 고급 개념 이해), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/educative/understanding-advanced-concepts-in-typescript-9bn텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)