728x90
LitererType 리터럴 타입
const userName1 = 'bob'; // 문자열 리터럴 타입
let userName2 = 'tom';
const는 불변값이며 let은 스트링 타입으로 고정되어있기에 다른 타입의 값을 배정하면 안된다
다른 타입도 넣을려면
let userName3: string | number = 'Tom';
userName3 = 3;
타입으로도 만들 수 있다.
type Job = 'police' | 'developer' | 'teacher';
숫자형 리터럴 타입도 이용할 수 있다.
type Grade = 1 | 2 | 3;
interface User {
name: string;
job: Job;
grade: Grade;
}
const user: User = {
name: "bob",
job: 'developer',
grade: 3
// 이때 타입에 존재하지 않는 값을 사용하게 된다면 에러가 발생한다.
}
UnionType 유니온 타입
동일한 속성의 타입을 다르게해서 구별가능한 것이 식별가능한 유니온타입
interface Car {
name: 'car';
color: string;
start(): void;
}
interface Mobile {
name:'mobile';
color: string;
call(): void;
}
const getGift = (gift: Car | Mobile) =>{
console.log(gift.color);
// gift.start();
//둘다 가지고 있는지 확인해야 사용 가능하다.
if(gift.name === 'car'){
gift.start();
}
else{
gift.call();
}
}
IntersectionType 교차타입
여러 타입을 합쳐서 사용함
교차타입은 여러개의 타입을 하나의 타입으로 합쳐
필요한 모든 기능을 갖은 하나의 타입이 만들어진다.
interface Car2 {
name: string;
start(): void;
}
interface Toy {
name:string;
color: string;
price: number;
}
const toyCar: Toy&Car2 = {
name: '타요',
start(){},
color: 'red',
price: 1000,
}
접근제한자 Access modifier - public, private, protected
public : 자식클래스나 클래스 인스턴스에서 접근 가능하다
private : 해당 클래스 내부에서만 접근 가능
protected : 자식 클래스에서는 접근 가능하나 클래스 인스턴스로는 접근
class Car{
color: string;
// 타입스크립트에서 this를 사용할 때는 맴버변수를 미리 선언해야한다.
constructor(color: string){
this.color = color;
}
start(){
console.log('start');
}
}
const bmw = new Car('red');
class Car2{
name: string = 'car';
color: string;
static wheels = 4;
// static property static을 사용하면 정적 맴버 변수를 만들 수 있다.
constructor(color:string){
this.color = color;
}
start(){
console.log('start');
console.log(this.name)
console.log(Car2.wheels)
// static으로 선언된 정적 맴버 변수나 메서드는
// 사용하려면 this가 아닌 클래스 명을 적어줘야한다.
}
}
class Bmw extends Car2{
constructor(color:string){
super(color);
}
showName(){
console.log(super.name);
}
doSomeThing(){
alert(3);
}
}
const z4 = new Bmw('black');
z4.name = "sss"
추상 class
추상 class 상속받은 쪽에서 구체화 해줘야한다.
abstract class Car2{
name: string = 'car';
color: string;
static wheels = 4;
// static property static을 사용하면 정적 맴버 변수를 만들 수 있다.
constructor(color:string){
this.color = color;
}
start(){
console.log('start');
console.log(this.name)
console.log(Car2.wheels)
// static으로 선언된 정적 맴버 변수나 메서드는
// 사용하려면 this가 아닌 클래스 명을 적어줘야한다.
}
abstract doSomeThing(): void;
// 추상 class 상속받은 쪽에서 구체화 해줘야한다.
}
class Bmw extends Car2{
constructor(color:string){
super(color);
}
showName(){
console.log(super.name);
}
doSomeThing(){
alert(3);
}
}
const z4 = new Bmw('black');
z4.name = "sss"
728x90
'TypeScript' 카테고리의 다른 글
type과 interface 중 뭐가 더 좋을까? (0) | 2024.07.11 |
---|---|
에러) element implicitly has an 'any' type because expression of type 'string' can't be used to index type (1) | 2024.02.08 |
TypeScript 속성 학습 - 3 (0) | 2023.01.27 |
TypeScript 속성 학습 - 1 (1) | 2023.01.24 |