2016-06-19 6 views
6

문자열 리터럴이 일치하지 않는다고 알려주는 TypeScript와 관련하여 매우 이상한 오류가 발생했습니다. (타이프 라이터의 V1.8)TypeScript React 네이티브 문자열 리터럴 지정 오류

import { Component } from "react"; 
import { 
    StyleSheet, 
    Text, 
    View 
} from "react-native"; 

const styles = StyleSheet.create({ 
    container: { 
    flex: 1, 
    justifyContent: "center", 
    alignItems: "center", 
    backgroundColor: "#F5FCFF", 
    }, 
    welcome: { 
    fontSize: 20, 
    textAlign: "center", 
    margin: 10, 
    } 
}); 

export class App extends Component<any, any> { 
    render() { 
    return (
     <View style={styles.container}> 
     <Text style={styles.welcome}> 
      Welcome to React Native! 
     </Text> 
     </View> 
    ); 
    } 
} 

오류 : 의 src \ 클라이언트 \의 index.ios.tsx (19,15) : 오류 TS2322 : 형식 '{fontSize는 : 번호; textAlign : string; margin : number; } '을 (를)'TextStyle '유형에 지정할 수 없습니다. 'textAlign'속성의 유형이 호환되지 않습니다. 'string'유형을 'auto'유형에 할당 할 수 없습니다. "왼쪽"| "맞다"| "센터"'. 'string'유형을 ''center ''유형에 지정할 수 없습니다.

올바른 입력을 설치했습니다. 다음은 TypeScript에서 작동하지 않는 것 같습니다.

interface Test { 
    a: "p" | "q" 
} 

let x : Test; 
let y = { 
    a: "p" 
} 

x = y; 

출처 :

<Text style={styles.welcome as any}> 

이유 :

유형을 유추가 declaraiton을 기반으로하는 https://blog.lopezjuri.com/2015/12/30/react-native--typescript/

+0

이 문제는 Typescript 2.1.x에서도 발생합니다. – Learner

답변

5

은 슬프게도 당신이 유형을 주장해야합니다. 문자열 리터럴은 내가 게임에 늦었 알고 있지만 그냥 같은 문제를 가로 질러 와서이 솔루션을 선호

let foo = "asdf"; // foo: string 

// Its a string becuase: 
foo = "something else"; // Would be strange if this would error 
12

때문에 ('어떤'그 이후 사용 싫어 (대신 문자열 리터럴의) string로 추정된다 때로는 유일한 옵션은 비록 가지), 타이프의 목적을 패배 :

import { Component } from "react"; 
import { 
    StyleSheet, 
    Text, 
    View 
} from "react-native"; 

interface Props { 
} 

interface State { 
} 

interface Style { 
    container: React.ViewStyle, 
    welcome: React.TextStyle 
} 

const styles = StyleSheet.create<Style>({ 
    container: { 
    flex: 1, 
    justifyContent: "center", 
    alignItems: "center", 
    backgroundColor: "#F5FCFF", 
    }, 
    welcome: { 
    fontSize: 20, 
    textAlign: "center", 
    margin: 10, 
    } 
}); 

export class App extends Component<Props, State> { 
    render() { 
    return (
     <View style={styles.container}> 
     <Text style={styles.welcome}> 
      Welcome to React Native! 
     </Text> 
     </View> 
    ); 
    } 
} 

우리는 빌드 오류를 만들 수있는 스타일의가 해결 될 때 어떤 유형 StyleSheet.create을 말한다면.

+3

환영 정의에서 구분되는 쉼표 바로 앞에 "container : {...}"정의 다음에 React.ViewStyle을 추가하는 것이 더 쉽고 깨끗해졌습니다. "다음과 같이"React.TextStyle " 환영합니다 : {...} "정의 그런 식으로 다른 사람이 새 파일을 추가하는 경우 스타일을 입력해야 할 필요가 있습니다. –