2013-03-13 3 views
2

문자열을 문자열로 생각합니다. 문자열이 깨진 그러나 문자열의 생각 : 또한문자열이 문자열이 아닙니다.

var str1:String = "asdf"; 
var str2:String = new String("asdf"); 
var str3:string = "asdf"; 
var str4:string = new String("asdf"); // Error 

Try It

:

var interfaceBased:String = "123"; 
var keywordBased:string ="123"; 
interfaceBased=keywordBased; 
keywordBased=interfaceBased; // Error 

Try It

이 알려진 컴파일러의 버그인가?

+0

http://typescript.codeplex.com/workitem/810 – basarat

+1

가능한 복제본 [Typescript : 문자열과 문자열의 차이] (http://stackoverflow.com/questions/14727044/typescript-difference-between-string) - 및 - 문자열) – JcFx

답변

5

String은 자바 스크립트 유형이고 string은 Typescript 유형입니다. 나는 버크 (quirk)라고 생각하지 않는다. 주로 String() 생성자를 문자열 리터럴 이상으로 사용할 이유가 없기 때문입니다.

는 여기를 참조하십시오 : 이것은 자바 스크립트 특질에서 유래 Typescript: difference between String and string

3

을 : 원시 문자열과 대상 문자열이 있습니다.

typeof "Hi! I'm a string!" // => "string" 

그러나 new을 사용하는 시간, 당신은 원시적보다는 객체를 생성 :

typeof new String("Hi! I'm a string!") // => "object" 

자바 스크립트를 암시 적 객체 문자열을 생성하는 기본 문자열은 일상 문자열, 물론입니다

var s = "Hi! I'm a string!"; 
s.property = 6; // s implicitly coerced to object string, property added 
console.log(s.property); // => undefined 
// property was added to the object string, but then the object string was 
// discarded as s still contained the primitive string. then s was coerced again 
// and the property was missing as it was only added to an object whose reference 
// was immediately dropped. 

개체 문자열을 원하는 경우가 거의 없기 때문에 속성에 액세스 할 때마다 원시 문자열을 사용할 수 있습니다. (예 : 빈 객체 문자열이 사실임) new String을 사용하는 대신 거의 항상 String을 원할 것입니다. 타이프에서이 문제를 표면하지만, 원시/객체의 구분과 특히 truthiness 문제가 Boolean 매우 이상한 될 경우

typeof String(new String("Hi! I'm a string!")) // => "string" 

가 나도 몰라 : new없이 String 심지어 원시 문자열로 다시 객체 문자열을 변환 할 수 있습니다 . 예를 들어 : 한마디로

var condition = new Boolean(false); 
if(condition) { // always true; objects are always truthy 
    alert("The world is ending!"); 
} 

,이 때문에 객체/원시 구별합니다. 거의 항상 옵션이있는 프리미티브를 원합니다.