본문 바로가기
Frontend/TypeScript(완)

[TS] TS연습하기15 : index signature, keyof 연산자

by VictorMeredith 2023. 4. 13.

//index signature 문법
interface StringOnly {
  [key : string] : string 
  //모든 문자로된 속성은 string 타입이다.
}

const car이다:StringOnly = {
  name : 'carName',
  age : '32', //string이어야 한다.
}


//깊은 object의 type (Recursive) : 쓸 일이 거의 없다.
interface TypeFont {
  'font-size': TypeFont|number
}

const cssFont:TypeFont = {
  'font-size':{
    'font-size':{
      'font-size' : 123
    }
  }
}


// 조건부 타입변환기(keyof 연산자)
type Car1 = { //type을 잘못 지정한 경우
  color : boolean,
  model : boolean,
  price : boolean | number
}

type TypeChanger<MyType> = { //생성
  [key in keyof MyType] : string
}

type NewType = TypeChanger<Car1> //실행 : 전부 다 string 으로 변한다.

const realCar:NewType = {
  color : 'red',
  model: 'super',
  price : '얼마'
}

 

댓글