1. 객체 구조에 사용
interface User { username: string, password: string, email?: string // this is optional property }
2. 지원 확장:
interface Address { street: string, city: string } interface User extends Address { username: string, password: string, email?: string }
3. 클래스는 인터페이스를 구현할 수 있습니다.
class Admin implements User { username: string password: string email?: string street: string city: string constructor(username: string, password:string, street:string, city:string, email?:string){ this.username = username; this.password = password; this.email = email || ''; this.street = street; this.city = city; }; } var aAdmin = new Admin("user1", "123", "3/2 street", "hcmc"); console.log(aAdmin);
출력:
Admin { username: 'user1', password: '123', email: '', street: '3/2 street', city: 'hcmc' }
4. 함수 선언 가능
interface AddUser{ (name: string) : void; } const user : AddUser = (name) => console.log(`Hello ${name}`);
1. 모든 유형의 별칭:
type UserType = { id: string, name: string } type ID = string | number; //Union type
2. 지원 교차로 유형:
type UserType = { id: string, name: string } type AddressType = { street: string, city: string, } type UserWithAddress = UserType & AddressType;
3. 지원 튜플:
type Coordinates = [number, number]; const point: Coordinates = [10, 20];
4. 다시 열 수 없음:
class AdminType extends UserType { // ERROR: 'UserType' only refers to a type, but is being used as a value here.ts(2693) }
Aspect | Interface | Type |
---|---|---|
Usage | Define Object structure | Flexible: can be define objects, unions, intersections, tuples. |
Extensibility | Can be extended using extends | Can be combined using & (intersection). |
Reopen/Declartion | Can be reopened to add new properties. | Cannot be reopened. |
Primitive Type | Cannot represent primitives directly. | Can alias primitive (e.g,.type ID = string); |
Union and Typle Support | Not supported. | Fully supported |
interface User { username: string, password: string, email?: string // this is optional property }
interface Address { street: string, city: string } interface User extends Address { username: string, password: string, email?: string }
class Admin implements User { username: string password: string email?: string street: string city: string constructor(username: string, password:string, street:string, city:string, email?:string){ this.username = username; this.password = password; this.email = email || ''; this.street = street; this.city = city; }; } var aAdmin = new Admin("user1", "123", "3/2 street", "hcmc"); console.log(aAdmin);
위 내용은 Typescript의 유형 및 인터페이스 이해의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!