ts基础
- 类型系统:变量和函数的类型声明(如
string,number,boolean等)。 - 接口(Interfaces):如何使用接口定义数据结构。
- 类(Classes):了解类的定义和使用,包括类的构造函数和方法。
- 装饰器(Decorators):Angular 中的组件、模块等都是用装饰器定义的,如
@Component,@NgModule等。
1. 基础类型
TypeScript 支持以下常用的基础类型:
-
number:数字类型,包括整数和浮点数。
let age: number = 30 -
string:字符串类型,用来存储文本。
let name: string = "Alice"; -
boolean:布尔类型,值为
true或false。let isActive: boolean = true; -
array:数组类型,可以指定数组中元素的类型。
let numbers: number[] = [1, 2, 3]; -
tuple:元组类型,用于固定长度和类型的数组。
let user: [string, number] = ["Alice", 30] -
enum:枚举类型,定义一组命名常量。
enum Color { Red, Green, Blue }let color: Color = Color.Green; -
any:任意类型,适用于不确定的变量类型,但不建议频繁使用。
let randomValue: any = "hello";randomValue = 5; // 可以重新赋值为其他类型 -
void:无返回值,通常用于函数没有返回值的情况。
function logMessage(): void {console.log("This is a message");} -
null 和 undefined:表示变量为空或未定义。
let u: undefined = undefined;let n: null = null;
2. 类型注解
可以在变量、参数和返回值上添加类型注解,便于代码提示和错误检查。
let name: string = "Alice";function greet(name: string): string { return `Hello, ${name}`;}3. 接口(Interfaces)
接口用于定义对象的结构(即包含哪些属性和方法),有助于实现代码的重用和灵活性。
interface Person { name: string; age: number; greet(): string;}
let alice: Person = { name: "Alice", age: 30, greet() { return `Hello, my name is ${this.name}`; }};4. 类(Classes)
TypeScript 支持面向对象编程,允许使用类和继承。类包含构造函数、属性和方法。
class Animal { name: string;
constructor(name: string) { this.name = name; }
move(distance: number = 0) { console.log(`${this.name} moved ${distance} meters.`); }}
let dog = new Animal("Dog");dog.move(10);- 访问修饰符
TypeScript 提供三种访问修饰符来控制类成员的访问权限:
- public:公共的,默认修饰符,任何地方都可以访问。
- private:私有的,只能在类内部访问。
- protected:受保护的,允许在类内部及继承的子类中访问。
class Person { public name: string; private age: number; protected address: string;
constructor(name: string, age: number, address: string) { this.name = name; this.age = age; this.address = address; }}5. 泛型(Generics)
泛型允许定义函数、类或接口时不指定类型,而在使用时再指定类型。这提高了代码的复用性。
function identity<T>(arg: T): T { return arg;}
let output = identity<string>("Hello"); // T 被推断为 string6. 类型推断
TypeScript 会根据代码自动推断变量的类型,如果没有显式声明类型,TypeScript 会根据赋值自动判断类型。
let x = 10; // TypeScript 自动推断 x 为 number7. 联合类型(Union Types)
联合类型允许一个变量接受多种类型值,使用 | 符号定义。
let value: string | number;value = "Hello";value = 42;8. 类型别名(Type Aliases)
使用 type 关键字可以为类型定义别名,便于复用。
type ID = string | number;let userId: ID = "123";9. 类型断言(Type Assertions)
类型断言告诉编译器某个值的具体类型,适用于我们比 TypeScript 更清楚变量的类型的情况。
let someValue: any = "This is a string";let strLength: number = (someValue as string).length;10. 装饰器(Decorators)
装饰器是 TypeScript 的高级特性,允许在类、方法或属性上应用一些元数据。Angular 中大量使用了装饰器来定义组件、模块等。
function log(target: any, key: string) { console.log(`${key} was called`);}
class Person { @log greet() { console.log("Hello!"); }}11. 模块和命名空间
-
模块:TypeScript 支持 ES6 模块系统,可以通过
import和export实现模块的导入和导出。module.ts export const pi = 3.14;// main.tsimport { pi } from './module';console.log(pi); -
命名空间:TypeScript 提供了命名空间(namespace)来组织代码,适用于大型应用。
namespace Geometry {export function calculateArea(radius: number): number {return Math.PI * radius * radius;}}console.log(Geometry.calculateArea(5));
TypeScript Basics
- Type System: Type declarations for variables and functions (e.g.,
string,number,booleanetc). - Interfaces: How to define data structures using interfaces.
- Classes: Understand class definitions and usage, including constructors and methods.
- Decorators: In Angular, components, modules, etc. are defined using decorators, such as
@Component,@NgModuleetc.
1. Basic Types
TypeScript supports the following common primitive types:
-
number: numeric type, including integers and floating-point numbers.
let age: number = 30 -
string: string type, used to store text.
let name: string = "Alice"; -
boolean: boolean type, values are
trueorfalse.let isActive: boolean = true; -
array: array type, can specify the element type.
let numbers: number[] = [1, 2, 3]; -
tuple: tuple type, for fixed-length arrays with specified types.
let user: [string, number] = ["Alice", 30] -
enum: enumeration type, defines a set of named constants.
enum Color { Red, Green, Blue }let color: Color = Color.Green; -
any: any type, suitable for variables of uncertain type, but not recommended to use frequently.
let randomValue: any = "hello";randomValue = 5; // can be reassigned to other types -
void: no return value, typically used for functions that do not return a value.
function logMessage(): void {console.log("This is a message");} -
null and undefined: represent empty or undefined variables.
let u: undefined = undefined;let n: null = null;
2. Type Annotations
You can add type annotations to variables, parameters, and return values to aid code completion and error checking.
let name: string = "Alice";function greet(name: string): string { return `Hello, ${name}`;}3. Interfaces
Interfaces are used to define the structure of objects (i.e., which properties and methods they have), helping to achieve code reuse and flexibility.
interface Person { name: string; age: number; greet(): string;}
let alice: Person = { name: "Alice", age: 30, greet() { return `Hello, my name is ${this.name}`; }};4. Classes
TypeScript supports object-oriented programming, allowing the use of classes and inheritance. Classes include constructors, properties, and methods.
class Animal { name: string;
constructor(name: string) { this.name = name; }
move(distance: number = 0) { console.log(`${this.name} moved ${distance} meters.`); }}
let dog = new Animal("Dog");dog.move(10);- Access Modifiers
TypeScript provides three access modifiers to control the accessibility of class members:
- public: public, the default modifier; accessible anywhere.
- private: private; only accessible within the class.
- protected: protected; accessible within the class and in subclasses.
class Person { public name: string; private age: number; protected address: string;
constructor(name: string, age: number, address: string) { this.name = name; this.age = age; this.address = address; }}5. Generics
Generics allow defining functions, classes, or interfaces without specifying a type, and specify the type at use time. This increases code reuse.
function identity<T>(arg: T): T { return arg;}
let output = identity<string>("Hello"); // T inferred as string6. Type Inference
TypeScript automatically infers the type of variables from the code; if no explicit type is declared, TypeScript infers it from the assigned value.
let x = 10; // TypeScript automatically infers x as number7. Union Types
Union types allow a variable to hold multiple types of values, defined using the | symbol.
let value: string | number;value = "Hello";value = 42;8. Type Aliases
Use the type keyword to define type aliases for reuse.
type ID = string | number;let userId: ID = "123";9. Type Assertions
Type assertions tell the compiler the specific type of a value, useful when we know more about the variable than TypeScript does.
let someValue: any = "This is a string";let strLength: number = (someValue as string).length;10. Decorators
Decorators are an advanced feature in TypeScript that allow attaching metadata to classes, methods, or properties. Decorators are heavily used in Angular to define components, modules, etc.
function log(target: any, key: string) { console.log(`${key} was called`);}
class Person { @log greet() { console.log("Hello!"); }}11. Modules and Namespaces
- Modules: TypeScript supports the ES6 module system; modules can be imported and exported using
importandexport.
export const pi = 3.14;
// main.tsimport { pi } from './module';console.log(pi);- Namespaces: TypeScript provides namespaces to organize code, suitable for large applications.
namespace Geometry { export function calculateArea(radius: number): number { return Math.PI * radius * radius; }}
console.log(Geometry.calculateArea(5));
TypeScript の基礎
- 型システム:変数と関数の型宣言(例として
string,number,booleanなど)。 - インターフェース(Interfaces):データ構造を定義する方法。
- クラス(Classes):クラスの定義と使用方法、コンストラクタやメソッドを含む。
- デコレータ(Decorators):Angular ではコンポーネントやモジュールなどがデコレータで定義されており、例として
@Component、@NgModuleなど。
1. 基本の型
TypeScript は以下の一般的な基本型をサポートします:
-
number:数値型、整数と浮動小数点数を含む。
let age: number = 30 -
string:文字列型、テキストの保存に用いる。
let name: string = "Alice"; -
boolean:真偽値型、値は
trueまたはfalse。let isActive: boolean = true; -
array:配列型、配列の要素の型を指定できます。
let numbers: number[] = [1, 2, 3]; -
tuple:タプル型、固定長と型の配列に用いる。
let user: [string, number] = ["Alice", 30] -
enum:列挙型、名前付き定数の集合を定義します。
enum Color { Red, Green, Blue }let color: Color = Color.Green; -
any:任意型、不確定な変数型に適用しますが、頻繁な使用は推奨されません。
let randomValue: any = "hello";randomValue = 5; // 他の型に再代入可能 -
void:戻り値がなく、通常は関数に戻り値がない場合に用います。
function logMessage(): void {console.log("This is a message");} -
null と undefined:変数が空または未定義であることを示します。
let u: undefined = undefined;let n: null = null;
2. 型注釈
変数、引数、戻り値に型注釈を追加することで、コード補完とエラーチェックを容易にします。
let name: string = "Alice";function greet(name: string): string { return `Hello, ${name}`;}3. インターフェース(Interfaces)
インターフェースはオブジェクトの構造(どの属性とメソッドが含まれるか)を定義するため、コードの再利用性と柔軟性の実現に役立ちます。
interface Person { name: string; age: number; greet(): string;}
let alice: Person = { name: "Alice", age: 30, greet() { return `Hello, my name is ${this.name}`; }};4. クラス(Classes)
TypeScript はオブジェクト指向プログラミングをサポートし、クラスと継承の使用を許可します。クラスにはコンストラクター、属性、メソッドが含まれます。
class Animal { name: string;
constructor(name: string) { this.name = name; }
move(distance: number = 0) { console.log(`${this.name} moved ${distance} meters.`); }}
let dog = new Animal("Dog");dog.move(10);- アクセス修飾子
TypeScript はクラスメンバーのアクセス権を制御する3つのアクセス修飾子を提供します:
- public:公開、デフォルトの修飾子で、どこからでもアクセスできます。
- private:プライベート、クラス内部でのみアクセス可能。
- protected:プロテクト、クラス内部および継承したサブクラスでアクセス可能。
class Person { public name: string; private age: number; protected address: string;
constructor(name: string, age: number, address: string) { this.name = name; this.age = age; this.address = address; }}5. ジェネリクス(Generics)
ジェネリクスは、関数・クラス・インターフェースを定義する際に型を指定せず、使用時に型を指定することを可能にします。これによりコードの再利用性が高まります。
function identity<T>(arg: T): T { return arg;}
let output = identity<string>("Hello"); // T が string に推論される6. 型推論
TypeScript はコードに基づいて自動的に変数の型を推論します。明示的な型宣言がない場合、型は代入に基づいて自動的に判断されます。
let x = 10; // TypeScript は自動的に x を number と推論7. ユニオン型(Union Types)
ユニオン型は、1つの変数が複数の型の値を受け取ることを許容します。| 記号を使用して定義します。
let value: string | number;value = "Hello";value = 42;8. 型エイリアス(Type Aliases)
type キーワードを使用して型のエイリアスを定義し、再利用を容易にします。
type ID = string | number;let userId: ID = "123";9. 型アサーション(Type Assertions)
型アサーションは、コンパイラに特定の値の具体的な型を伝え、TypeScript よりも変数の型をよく知っている場合に適用します。
let someValue: any = "This is a string";let strLength: number = (someValue as string).length;10. デコレータ(Decorators)
デコレータは TypeScript の高度な機能で、クラス・メソッド・プロパティにメタデータを適用することを許可します。Angular ではデコレータを使ってコンポーネントやモジュールなどを多用します。
function log(target: any, key: string) { console.log(`${key} was called`);}
class Person { @log greet() { console.log("Hello!"); }}11. モジュールと名前空間
-
モジュール:TypeScript は ES6 モジュールシステムをサポートしており、
importとexportを使ってモジュールのインポートとエクスポートを実現します。module.ts export const pi = 3.14;// main.tsimport { pi } from './module';console.log(pi); -
名前空間:TypeScript はコードを整理するための名前空間(namespace)を提供します。大規模なアプリケーションに適しています。
namespace Geometry {export function calculateArea(radius: number): number {return Math.PI * radius * radius;}}console.log(Geometry.calculateArea(5));
部分信息可能已经过时









