모든 개발자가 알아야 할 최고의 고급 타이프스크립트 개념
TypeScript는 추가된 유형 안전성으로 인해 JavaScript보다 종종 선호되는 현대 프로그래밍 언어입니다. 이 기사에서는 TypeScript 프로그래밍 기술을 연마하는 데 도움이 되는 상위 10가지 TypeScript 개념을 공유하겠습니다. 준비되셨나요?가세요.
1.Generics : 제네릭을 사용하면 재사용 가능한 유형을 만들 수 있으며 이는 현재의 데이터는 물론 미래의 데이터를 처리하는 데 도움이 될 것입니다.
제네릭의 예:
인수를 일부 유형으로 취하는 Typescript의 함수를 원할 수도 있고 동일한 유형을 반환하기를 원할 수도 있습니다.
function func<T>(args:T):T{ return args; }
2.유형 제약 조건이 있는 제네릭 : 이제 문자열과 정수만 허용하도록 정의하여 T 유형을 제한해 보겠습니다.
function func<T extends string | number>(value: T): T { return value; } const stringValue = func("Hello"); // Works, T is string const numberValue = func(42); // Works, T is number // const booleanValue = func(true); // Error: Type 'boolean' is not assignable to type 'string | number'
3.일반 인터페이스:
인터페이스 제네릭은 다양한 유형과 함께 작동하는 개체, 클래스 또는 함수에 대한 계약(모양)을 정의하려는 경우 유용합니다. 이를 통해 구조를 일관되게 유지하면서 다양한 데이터 유형에 적응할 수 있는 청사진을 정의할 수 있습니다.
// Generic interface with type parameters T and U interface Repository<T, U> { items: T[]; // Array of items of type T add(item: T): void; // Function to add an item of type T getById(id: U): T | undefined; // Function to get an item by ID of type U } // Implementing the Repository interface for a User entity interface User { id: number; name: string; } class UserRepository implements Repository<User, number> { items: User[] = []; add(item: User): void { this.items.push(item); } getById(idOrName: number | string): User | undefined { if (typeof idOrName === 'string') { // Search by name if idOrName is a string console.log('Searching by name:', idOrName); return this.items.find(user => user.name === idOrName); } else if (typeof idOrName === 'number') { // Search by id if idOrName is a number console.log('Searching by id:', idOrName); return this.items.find(user => user.id === idOrName); } return undefined; // Return undefined if no match found } } // Usage const userRepo = new UserRepository(); userRepo.add({ id: 1, name: "Alice" }); userRepo.add({ id: 2, name: "Bob" }); const user1 = userRepo.getById(1); const user2 = userRepo.getById("Bob"); console.log(user1); // Output: { id: 1, name: "Alice" } console.log(user2); // Output: { id: 2, name: "Bob" }
4.일반 클래스:: 클래스의 모든 속성이 일반 매개변수로 지정된 유형을 따르도록 하려면 이 옵션을 사용하세요. 이를 통해 클래스의 모든 속성이 클래스에 전달된 유형과 일치하도록 보장하면서 유연성을 확보할 수 있습니다.
interface User { id: number; name: string; age: number; } class UserDetails<T extends User> { id: T['id']; name: T['name']; age: T['age']; constructor(user: T) { this.id = user.id; this.name = user.name; this.age = user.age; } // Method to get user details getUserDetails(): string { return `User: ${this.name}, ID: ${this.id}, Age: ${this.age}`; } // Method to update user name updateName(newName: string): void { this.name = newName; } // Method to update user age updateAge(newAge: number): void { this.age = newAge; } } // Using the UserDetails class with a User type const user: User = { id: 1, name: "Alice", age: 30 }; const userDetails = new UserDetails(user); console.log(userDetails.getUserDetails()); // Output: "User: Alice, ID: 1, Age: 30" // Updating user details userDetails.updateName("Bob"); userDetails.updateAge(35); console.log(userDetails.getUserDetails()); // Output: "User: Bob, ID: 1, Age: 35" console.log(new UserDetails("30")); // Error: "This will throw error"
5.유형 매개변수를 전달된 유형으로 제한: 때때로 매개변수 유형이 전달된 다른 매개변수에 종속되기를 원할 때가 있습니다. 혼란스러울 것 같지만 아래 예를 살펴보겠습니다.
function getProperty<Type>(obj: Type, key: keyof Type) { return obj[key]; } let x = { a: 1, b: 2, c: 3 }; getProperty(x, "a"); // Valid getProperty(x, "d"); // Error: Argument of type '"d"' is not assignable to parameter of type '"a" | "b" | "c"'.
6.조건부 유형 : 종종 우리는 유형이 한 유형이거나 다른 유형이기를 원합니다. 이런 상황에서는 조건부 유형을 사용합니다.
간단한 예는 다음과 같습니다.
function func(param:number|boolean){ return param; } console.log(func(2)) //Output: 2 will be printed console.log(func("True")) //Error: boolean cannot be passed as argument
조금 복잡한 예:
type HasProperty<T, K extends keyof T> = K extends "age" ? "Has Age" : "Has Name"; interface User { name: string; age: number; } let test1: HasProperty<User, "age">; // "Has Age" let test2: HasProperty<User, "name">; // "Has Name" let test3: HasProperty<User, "email">; // Error: Type '"email"' is not assignable to parameter of type '"age" | "name"'.
6.교차 유형: 이러한 유형은 여러 유형을 하나로 결합하여 특정 유형이 다양한 다른 유형의 속성과 동작을 상속할 수 있도록 할 때 유용합니다.
이에 대한 흥미로운 예를 살펴보겠습니다.
// Defining the types for each area of well-being interface MentalWellness { mindfulnessPractice: boolean; stressLevel: number; // Scale of 1 to 10 } interface PhysicalWellness { exerciseFrequency: string; // e.g., "daily", "weekly" sleepDuration: number; // in hours } interface Productivity { tasksCompleted: number; focusLevel: number; // Scale of 1 to 10 } // Combining all three areas into a single type using intersection types type HealthyBody = MentalWellness & PhysicalWellness & Productivity; // Example of a person with a balanced healthy body const person: HealthyBody = { mindfulnessPractice: true, stressLevel: 4, exerciseFrequency: "daily", sleepDuration: 7, tasksCompleted: 15, focusLevel: 8 }; // Displaying the information console.log(person);
7.infer 키워드: infer 키워드는 특정 유형을 조건부로 판단할 때 유용하며, 조건이 충족되면 해당 유형에서 하위 유형을 추출할 수 있습니다.
일반적인 구문은 다음과 같습니다.
type ConditionalType<T> = T extends SomeType ? InferredType : OtherType;
예:
type ReturnTypeOfPromise<T> = T extends Promise<infer U> ? U : number; type Result = ReturnTypeOfPromise<Promise<string>>; // Result is 'string' type ErrorResult = ReturnTypeOfPromise<number>; // ErrorResult is 'never' const result: Result = "Hello"; console.log(typeof result); // Output: 'string'
8.유형 분산 : 이 개념은 하위 유형과 상위 유형이 어떻게 서로 관련되어 있는지를 나타냅니다.
두 가지 유형이 있습니다:
공분산: 상위 유형이 필요한 경우 하위 유형을 사용할 수 있습니다.
이에 대한 예를 살펴보겠습니다.
function func<T>(args:T):T{ return args; }
위의 예에서 Car는 Vehicle 클래스에서 속성을 상속받았으므로 하위 유형이 상위 유형이 갖는 모든 속성을 가지므로 상위 유형이 예상되는 하위 유형에 이를 할당하는 것이 절대적으로 유효합니다.
반공변성: 이는 공분산의 반대입니다. 하위 유형이 있을 것으로 예상되는 곳에 상위 유형을 사용합니다.
function func<T extends string | number>(value: T): T { return value; } const stringValue = func("Hello"); // Works, T is string const numberValue = func(42); // Works, T is number // const booleanValue = func(true); // Error: Type 'boolean' is not assignable to type 'string | number'
반공변성을 사용할 때는 하위 유형에 특정한 속성이나 메서드에 액세스하지 않도록 주의해야 합니다. 이로 인해 오류가 발생할 수 있습니다.
9. 반영: 이 개념에는 런타임에 변수 유형을 결정하는 것이 포함됩니다. TypeScript는 주로 컴파일 시 유형 검사에 중점을 두지만 여전히 TypeScript 연산자를 활용하여 런타임 중에 유형을 검사할 수 있습니다.
typeof 연산자: typeof 연산자를 사용하여 런타임에 변수 유형을 찾을 수 있습니다
// Generic interface with type parameters T and U interface Repository<T, U> { items: T[]; // Array of items of type T add(item: T): void; // Function to add an item of type T getById(id: U): T | undefined; // Function to get an item by ID of type U } // Implementing the Repository interface for a User entity interface User { id: number; name: string; } class UserRepository implements Repository<User, number> { items: User[] = []; add(item: User): void { this.items.push(item); } getById(idOrName: number | string): User | undefined { if (typeof idOrName === 'string') { // Search by name if idOrName is a string console.log('Searching by name:', idOrName); return this.items.find(user => user.name === idOrName); } else if (typeof idOrName === 'number') { // Search by id if idOrName is a number console.log('Searching by id:', idOrName); return this.items.find(user => user.id === idOrName); } return undefined; // Return undefined if no match found } } // Usage const userRepo = new UserRepository(); userRepo.add({ id: 1, name: "Alice" }); userRepo.add({ id: 2, name: "Bob" }); const user1 = userRepo.getById(1); const user2 = userRepo.getById("Bob"); console.log(user1); // Output: { id: 1, name: "Alice" } console.log(user2); // Output: { id: 2, name: "Bob" }
instanceof 연산자: instanceof 연산자를 사용하면 객체가 클래스의 인스턴스인지 특정 유형인지 확인할 수 있습니다.
interface User { id: number; name: string; age: number; } class UserDetails<T extends User> { id: T['id']; name: T['name']; age: T['age']; constructor(user: T) { this.id = user.id; this.name = user.name; this.age = user.age; } // Method to get user details getUserDetails(): string { return `User: ${this.name}, ID: ${this.id}, Age: ${this.age}`; } // Method to update user name updateName(newName: string): void { this.name = newName; } // Method to update user age updateAge(newAge: number): void { this.age = newAge; } } // Using the UserDetails class with a User type const user: User = { id: 1, name: "Alice", age: 30 }; const userDetails = new UserDetails(user); console.log(userDetails.getUserDetails()); // Output: "User: Alice, ID: 1, Age: 30" // Updating user details userDetails.updateName("Bob"); userDetails.updateAge(35); console.log(userDetails.getUserDetails()); // Output: "User: Bob, ID: 1, Age: 35" console.log(new UserDetails("30")); // Error: "This will throw error"
타사 라이브러리를 사용하여 런타임 시 유형을 결정할 수 있습니다.
10.종속성 주입: 종속성 주입은 실제로 코드를 생성하거나 관리하지 않고도 구성 요소에 코드를 가져올 수 있는 패턴입니다. 라이브러리를 사용하는 것처럼 보일 수 있지만 CDN이나 API를 통해 라이브러리를 설치하거나 가져올 필요가 없기 때문에 다릅니다.
얼핏 보면 코드 재사용이 가능하다는 점에서 재사용성을 위한 함수를 사용하는 것과 비슷해 보일 수도 있습니다. 그러나 구성 요소에서 직접 기능을 사용하면 구성 요소 간의 긴밀한 결합이 발생할 수 있습니다. 즉, 기능이나 논리의 변경은 해당 기능이 사용되는 모든 위치에 영향을 미칠 수 있습니다.
종속성 주입은 이를 사용하는 구성 요소에서 종속성 생성을 분리하여 코드를 더 유지 관리하고 테스트하기 쉽게 만들어 이 문제를 해결합니다.
의존성 주입이 없는 예
function getProperty<Type>(obj: Type, key: keyof Type) { return obj[key]; } let x = { a: 1, b: 2, c: 3 }; getProperty(x, "a"); // Valid getProperty(x, "d"); // Error: Argument of type '"d"' is not assignable to parameter of type '"a" | "b" | "c"'.
의존성 주입 예시
function func(param:number|boolean){ return param; } console.log(func(2)) //Output: 2 will be printed console.log(func("True")) //Error: boolean cannot be passed as argument
밀접하게 결합된 시나리오에서 오늘 MentalWellness 클래스에 스트레스 수준 속성이 있고 내일 다른 것으로 변경하기로 결정한 경우 해당 속성이 사용된 모든 위치를 업데이트해야 합니다. 이로 인해 많은 리팩토링 및 유지 관리 문제가 발생할 수 있습니다.
그러나 종속성 주입과 인터페이스를 사용하면 이 문제를 피할 수 있습니다. 생성자를 통해 종속성(예: MentalWellness 서비스)을 전달함으로써 특정 구현 세부 정보(예: 스트레스 레벨 특성)가 인터페이스 뒤에서 추상화됩니다. 즉, 인터페이스가 동일하게 유지되는 한 특성이나 클래스를 변경할 때 종속 클래스를 수정할 필요가 없습니다. 이 접근 방식을 사용하면 구성 요소를 긴밀하게 결합하지 않고 런타임에 필요한 것을 주입하므로 코드가 느슨하게 결합되고 유지 관리가 용이하며 테스트하기가 더 쉽습니다.
위 내용은 모든 개발자가 알아야 할 최고의 고급 타이프스크립트 개념의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











프론트 엔드 개발시 프론트 엔드 열지대 티켓 인쇄를위한 자주 묻는 질문과 솔루션, 티켓 인쇄는 일반적인 요구 사항입니다. 그러나 많은 개발자들이 구현하고 있습니다 ...

JavaScript는 현대 웹 개발의 초석이며 주요 기능에는 이벤트 중심 프로그래밍, 동적 컨텐츠 생성 및 비동기 프로그래밍이 포함됩니다. 1) 이벤트 중심 프로그래밍을 사용하면 사용자 작업에 따라 웹 페이지가 동적으로 변경 될 수 있습니다. 2) 동적 컨텐츠 생성을 사용하면 조건에 따라 페이지 컨텐츠를 조정할 수 있습니다. 3) 비동기 프로그래밍은 사용자 인터페이스가 차단되지 않도록합니다. JavaScript는 웹 상호 작용, 단일 페이지 응용 프로그램 및 서버 측 개발에 널리 사용되며 사용자 경험 및 크로스 플랫폼 개발의 유연성을 크게 향상시킵니다.

기술 및 산업 요구에 따라 Python 및 JavaScript 개발자에 대한 절대 급여는 없습니다. 1. 파이썬은 데이터 과학 및 기계 학습에서 더 많은 비용을 지불 할 수 있습니다. 2. JavaScript는 프론트 엔드 및 풀 스택 개발에 큰 수요가 있으며 급여도 상당합니다. 3. 영향 요인에는 경험, 지리적 위치, 회사 규모 및 특정 기술이 포함됩니다.

동일한 ID로 배열 요소를 JavaScript의 하나의 객체로 병합하는 방법은 무엇입니까? 데이터를 처리 할 때 종종 동일한 ID를 가질 필요가 있습니다 ...

JavaScript를 배우는 것은 어렵지 않지만 어려운 일입니다. 1) 변수, 데이터 유형, 기능 등과 같은 기본 개념을 이해합니다. 2) 마스터 비동기 프로그래밍 및 이벤트 루프를 통해이를 구현하십시오. 3) DOM 운영을 사용하고 비동기 요청을 처리합니다. 4) 일반적인 실수를 피하고 디버깅 기술을 사용하십시오. 5) 성능을 최적화하고 모범 사례를 따르십시오.

이 기사에서 시차 스크롤 및 요소 애니메이션 효과 실현에 대한 토론은 Shiseido 공식 웹 사이트 (https://www.shiseido.co.jp/sb/wonderland/)와 유사하게 달성하는 방법을 살펴볼 것입니다.

Console.log 출력의 차이의 근본 원인에 대한 심층적 인 논의. 이 기사에서는 Console.log 함수의 출력 결과의 차이점을 코드에서 분석하고 그에 따른 이유를 설명합니다. � ...

JavaScript의 최신 트렌드에는 Typescript의 Rise, 현대 프레임 워크 및 라이브러리의 인기 및 WebAssembly의 적용이 포함됩니다. 향후 전망은보다 강력한 유형 시스템, 서버 측 JavaScript 개발, 인공 지능 및 기계 학습의 확장, IoT 및 Edge 컴퓨팅의 잠재력을 포함합니다.
