2017-10-24 19 views
0

私はこのような単純な一枚持っている:右側にコンパイルされたバージョンを示しているが、それは、それはgetMethodpostMethod定数を見つけることができないというエラーが表示さTypeScript PlaygroundTypeScriptで定義された定数が見つからないのはなぜですか?

const getMethod = 'get'; 
const postMethod = 'post'; 

export type RequestMethod = getMethod | postMethod; 

を。

このコードで何が問題になっていますか?私は前にこのように消費していましたが、今はエラーが表示されます。ここで

は、エラーのスクリーンショットです:

error

答えて

1

組合の種類は2種類の労働組合であるspecあたり通り。定数は型ではありません。文字列リテラルは、再びspecに従った型です。そのため、 'get'を書くことができます。 '役職'。

あなたは、文字列リテラルの型になります定数の型を使用することができます:あなたがタイプとして定数を使用しようとしているため

const getMethod = 'get'; 
const postMethod = 'post'; 

export type RequestMethod = typeof getMethod | typeof postMethod; 
0

です。

RequestMethodをユニオンタイプにする場合は、代わりにgetMethodpostMethodをタイプとして定義する必要があります。

type getMethod = 'get'; 
type postMethod = 'post'; 

export type RequestMethod = getMethod | postMethod; 
+1

私は彼がコードの値を使用できるようにしたい、と書くことを避けるために望んでいるので、彼は、定数を定義して推測しています再び文字列。 –

0

getMethodtype | interface | enum等しない変数であると予想されます。

あなたは試すことができます:

type getMethod = 'get'; 
type postMethod = 'post'; 

export type RequestMethod = getMethod | postMethod; 

または

enum RequestMethod { 
    GET = 'get', 
    POST = 'post' 
} 

const getMethod = RequestMethod.GET; 

function makeRequest(method: RequestMethod) { 

} 
関連する問題