Type Script 4.5가 더 편리합니다!better-typescript-lib v2
12054 단어 TypeScripttech
필자는 TypeScript의 표준 라이브러리에서 제외
any
하여 더욱 안전한 better-typescript-lib를 개발하였으며, 이번에는 TypeScript4.5에 대응하는 v2를 개발하였다.베타 버전 0.02.0.0-beta
을 준비했다.이 글에는 벳터-typescript-lib의 간단한 소개 외에도 TypeScript4.5 기능에 대한 해설과 이로 인한 better-typescript-lib의 변화도 소개됐다.
영어판 기사도 준비했다.같이 보세요.
→
better-typescript-lib
better-typescript-lib는 TypeScript의 표준 라이브러리를 더욱 안전하게 설정합니다.ter-typescript-lib에서 더 안전한 예는
JSON.parse
와eval
가 있다.이러한 반환 값은 표준 Type Scriptany
입니다.// any 😩
const obj = JSON.parse('{"foo": 123}');
console.log(obj.foo); // 123
better-typescript-lib를 가져온 후JSON.parse
의 반환값은 JSONValue
,eval
의 반환값은 unknown
이다.JSONValue
JSON의 모든 값을 나타내는 UNION형입니다.이렇게 되면 any
형이 아니기 때문에 사용하기가 좀 번거롭지만 대신 안전하다.// JSONValue 😁
const obj = JSON.parse('{"foo": 123}');
if (isFooObject(obj)) {
console.log(obj.foo); // 123
}
function isFooObject(obj: JSONValue): obj is { foo: number } {
return isPropertyAccessible(obj) && typeof obj.foo === "number";
}
function isPropertyAccessible(obj: unknown): obj is Record<string, unknown> {
return obj !== null;
}
이렇게 쓰면 귀찮은 인상을 줄 수 있지만 꼭 해야 할 일이다.배제any
를 통해 반드시 해야 할 일을 확실하게 깨달을 수 있다.better-typescript-lib를 사용하면 이전any
에 숨겨진 오류를 발견할 수 있습니다.자세한 내용은 예전에 집필했던 이쪽 기사를 보십시오.
전통적인better-typescript-lib 가져오기 방법
이렇게 편리한better-typescript-lib는 이전에 가져오기가 좀 어려웠다.TypeScript에서 준비한 표준 라이브러리의 읽기를 무효화하고better-typescript-lib에 수동으로 읽어야 합니다.
구체적으로
npm i -D better-typescript-lib
, tsconfig.json
에 "noLib": true
를 쓴 다음에 응용 프로그램 코드에서 다음과 같은 내용을 읽어야 한다.이것은 그다지 예쁘지 않다.하크감도 컸다./// <reference path="./node_modules/better-typescript-lib/lib.es5.d.ts" />
/// <reference path="./node_modules/better-typescript-lib/lib.dom.d.ts" />
새better-typescript-lib 가져오기 방법 및 구조
Type Script4.5 이상을 지원하는 better-typescript-libv2에서 better-typescript-lib를 가져오려면 npm install만 필요합니다.즉, 다음 단계만 실행하고 수동으로 읽기는커녕 tsconfig입니다.심지어 제이슨을 고칠 필요도 없다.아주 간단하네요.
npm i -D [email protected]
TypeScript4.5 정식 버전이 발매되면 better-typescript-lib도 정식으로 v2를 발매한다.이후에는 필요 없음@2.0.0-beta
.최신 정보를 확인하십시오GitHub.이것을 가능하게 만드는 것은 Type Script 4.5에서 가져온 다음 기능입니다.
이것은
@typescript/lib-[lib]
라는 포장을 설치했을 때 표준 라이브러리의 lib.[lib].d.ts
대신 읽은 것이다.예를 들어 tsconfig.json에 "target": "es2015"
라고 쓰여 있으면 Type Script에 덧붙인 lib.es2015.d.ts
가 읽힌다. 이것은 이전의 행동이다. @typescript/lib-es2015
가 설치되어 있으면 이쪽이 바뀌어 읽힌다.따라서 향상된 유형 정의
@typescript/lib-es2015
를 설치하여 Type Script에서 읽은 유형 정의를 대체할 수 있습니다.또한 npm에서
@typescript
는 당연히 범위가 있는 타입 스크립트 팀이다.제3자는 이 포장 이름을publish라고 마음대로 할 수 없다.다행히도 npm(또는 패키지.json을 지원하는 다른 패키지 관리자)는 별명으로 패키지를 설치하는 기능을 지원한다.better-typescript-lib
의 package.json
내용은 다음과 같다. "dependencies": {
"@typescript/lib-dom": "npm:@better-typescript-lib/[email protected]",
"@typescript/lib-es2015": "npm:@better-typescript-lib/[email protected]",
"@typescript/lib-es2016": "npm:@better-typescript-lib/[email protected]",
"@typescript/lib-es2017": "npm:@better-typescript-lib/[email protected]",
"@typescript/lib-es2018": "npm:@better-typescript-lib/[email protected]",
"@typescript/lib-es2019": "npm:@better-typescript-lib/[email protected]",
"@typescript/lib-es2020": "npm:@better-typescript-lib/[email protected]",
"@typescript/lib-es2021": "npm:@better-typescript-lib/[email protected]",
"@typescript/lib-es5": "npm:@better-typescript-lib/[email protected]",
"@typescript/lib-esnext": "npm:@better-typescript-lib/[email protected]",
"@typescript/lib-header": "npm:@better-typescript-lib/[email protected]",
"@typescript/lib-scripthost": "npm:@better-typescript-lib/[email protected]",
"@typescript/lib-webworker": "npm:@better-typescript-lib/[email protected]"
}
이것은 @typescript/lib-dom
의 이름으로 설치@better-typescript-lib/[email protected]
한다는 뜻이다.이렇게 하면 원하는 포장을 @typescript/lib-[lib]
이라는 이름으로 설치할 수 있다.이것을 이용하면 우리가 준비한 유형 정의를 TypeScript에 읽을 수 있습니다. (이것도 좀 놀랍지만 TypeScript가 공식적으로 추천한 방법입니다.)이것들
better-typescript-lib
을 설치하면 TypeScript 컴파일러에서 볼 수 있습니다.modules의 내용을 평탄하게 하는 규격을 사용했기 때문이다.PnP 같은 경우라면 좋지 않을 수도 있지만, 요구에 따라 향후 대책이 논의될 수도 있다.그나저나 Type Script가 이런 기능을 도입한 것은 원래
@typescript/lib-[lib]
의 구상을 위해서였다. (아래의 issue 참조)TypeScript의 표준 라이브러리는 TypeScript의 버전이 업그레이드됨에 따라 달라지는데 그중
@types/web
의 변경은 후방 호환성 손상을 초래하기 쉽다.lib.dom.d.ts
를 @types/web
로 설치한 후 Type Script 버전 업그레이드의 영향을 받지 않고 독립적인 버전 관리를 수행할 수 있습니다.다양한 실현 방법이 있지만 현재@typescript/lib-dom
를 사용하는 방법은 의존자의 버전 관리 등을 기존의 패키지 관리자에 완전히 의뢰하기 위해 선택한 것이다.@typescript/lib-[lib]
설치의 단순성도 바로 이 은혜를 받았다.총결산
Type Script 4.5는 표준 라이브러리 유형 정의를 간단하게 대체하는 새로운 기능을 가져옵니다.기본값보다 안전한 표준 라이브러리
better-typescript-lib
를 제공하는 다음 주요 버전에서는 바로 이 기능을 사용할 수 있고 더욱 간단하게 설치할 수 있다.better-typescript-lib의 GiitHub(v2 공식 발표 전
better-typescript-lib
지점 참조)Reference
이 문제에 관하여(Type Script 4.5가 더 편리합니다!better-typescript-lib v2), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://zenn.dev/uhyo/articles/better-typescript-lib-v2텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)