2016-11-16 1 views
3

typescript에서 변수에 일반 객체 유형을 할당 할 수있는 방법이 있습니다. 여기 그것은 단지 자바 스크립트 객체가 변수 및 데이터의 다른 유형 (숫자, 문자열, 부울)typescript의 일반 객체 유형

답변

7

물론 일에 할당 할 수 있도록해야 즉 내가 '일반 Object 형'

let myVariable: GenericObject = 1 // Should throw an error 
           = 'abc' // Should throw an error 
           = {} // OK 
           = {name: 'qwerty'} //OK 

무엇을 의미입니다 :

type GenericObject = { [key: string]: any }; 

let myVariable1: GenericObject = 1; // Type 'number' is not assignable to type '{ [key: string]: any; }' 
let myVariable2: GenericObject = 'abc'; // Type 'string' is not assignable to type '{ [key: string]: any; }' 
let myVariable3: GenericObject = {} // OK 
let myVariable4: GenericObject = {name: 'qwerty'} //OK 

(code in playground)

2

타이프 2.2 당신이 사용할 수있는

let myVariable: object;