컴퓨터/HTML & JS & TS
ReScript: TypeScript와 비슷한 Javascript 파생 언어
두뇌미포함
2021. 2. 4. 22:19
728x90
반응형
ReScript
ReScript Documentation
The ReScript language and ecosystem docs
rescript-lang.org
1. 소개
Javascript 최적화, 파생 언어는 워낙 많다. 그중 TypeScript가 제일 잘 살아남은 것 같은데
찾아보니 ReScript란 OCaml 타입 시스템을 참고한 느낌의 언어도 있다.
새로 생긴 언어는 아니고 ReasonML (페이스북)과 BuckleScript (블룸버그)를 rebranding 한 것이다.
React에서도 사용할 수 있다. TypeScript나 JS에서 ReScript로 바꾸려면 시간이 꽤 걸릴 것 같다.
2. 문법
- 세미콜론 (;) 없음
- 주석 같음 (/*, //)
- String은 ", char은 ', 문자 연결은 ++,
- 튜플 (immutable, 정렬, 생성 시 고정 사이즈, 이종)
- null 없음 (대신 option은 있음)
- .res 란 이름의 파일 이름을 사용함
- ...
온라인에서 체험해 볼 수 있다. @링크
https://rescript-lang.org/try
rescript-lang.org
1. Hello World
Js.log("Hello World!")
2. Tuple (튜플)
let ageAndName: (int, string) = (24, "Lil' ReScript")
// a tuple type alias
type coord3d = (float, float, float)
let my3dCoordinates: coord3d = (20.0, 30.5, 100.0)
3. Type
Strong, Static, Sound, Fast, Inferred
컴파일러가 알아서 유추도 하지만 직접 타입을 설정해도 된다.
~은 라벨 파라미터이다, 파이썬에서 function(a=3)과 같은 느낌
let myInt = 5
let myInt: int = 5
let myInt = (5: int) + (4: int)
let add = (x: int, y: int) : int => x + y
let drawCircle = (~radius as r: int): circleType => /* code here */
4. String
파이썬 f-string처럼 string interpolation에서 j를 쓰면 쉽게 연결할 수 있다.
let name = "Joe"
let greeting = `Hello
World
👋
${name}
`
// JS: var name = "Joe";
// var greeting = "Hello\nWorld\n👋\n" + name + "\n";
let greetings = "Hello " ++ "world!"
// JS: var greetings = "Hello world!";
let age = 10
let message = j`Today I am $age years old.`
// JS: var message = "Today I am " + 10 + " years old.";
5. Optional
Some이란 문법이 있다.
Js.Option | ReScript API
The ReScript language and ecosystem docs
rescript-lang.org
let number = Some(5)
switch number {
| None =>
Js.log("The person doesn't have a car")
| Some(number) =>
Js.log("The person's license number is " ++ Js.Int.toString(number))
}
/* JS 결과
var number = 5;
if (number !== undefined) {
console.log("The person's license number is " + number.toString());
} else {
console.log("The person doesn't have a car");
}
*/
6. Pipe
함수형 프로그래밍 | 처럼 -> 키워드가 있다.
person
->parseData
->getAge
->validateAge
// JS 결과: validateAge(getAge(parseData(person)));
7. 함수
라벨을 지정하면 순서에 상관없이 이름에 맞는 위치로 간다.
let addCoordinates = (~x, ~y) => {
// use x and y here
}
// ...
addCoordinates(~y=6, ~x=5)
/* JS 결과
function addCoordinates(x, y) {
// use x and y here
}
addCoordinates(5, 6);
*/
8. 예제
type result =
| Success(string)
| Fail(string)
let displayMessage = (Success(m) | Fail(m)) => {
// we've directly extracted the success message
// string by destructuring the parameter
Js.log(m)
}
displayMessage(Success("You did it!"))
displayMessage(Fail("I Failed"))
/* JS 결과
function displayMessage(param) {
console.log(param._0);
}
displayMessage({
TAG: /* Success */0,
_0: "You did it!"
});
displayMessage({
TAG: /* Fail */1,
_0: "I Failed"
});
*/
728x90