本篇內容介紹了“TypeScript類型級別實例代碼分析”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
代碼如下:
/** * Try assigning "World" to `type Hello`! */ type Hello = "..."; // Type-level unit tests! // If the next line type-checks, you solved this challenge! type test1 = Expect<Equal<Hello, "World">>;
多年來,TypeScript的類型系統已經從基本的類型注釋發展成為一種大型復雜的編程語言。如果你曾經研究過一個開源庫的代碼,你可能會發現一些看起來很嚇人、很陌生的類型,比如來自另一個星球的一些深奧的語言。庫代碼通常需要比我們習慣編寫的代碼更抽象;
這就是為什么它廣泛使用高級TypeScript功能,如泛型、條件類型、映射類型甚至遞歸類型。我個人在研究TS Pattern時學習了這些概念,這是一個開源庫,具有極其難以鍵入的特殊性。在本課程中,我希望分享我通過閱讀過多的源代碼和對類型系統進行數百小時的修改所學到的知識。
類型之所以很棒,有很多原因:
類型可以作為代碼的文檔,以便查詢。
類型可以向開發人員提供代碼提示。
類型能發現錯誤和拼寫錯誤。
類型系統對您的代碼了解得越多,它對你的幫助就越大!一旦你精通TypeScript,一切都變得可能。您將不再覺得類型系統限制了您編寫所需抽象的能力。
想不想檢查路由參數傳遞的是否正確?
走你:
// ? this is correct ????
navigate("user/:userId", { userId: "2" });
// ? Looks good! `dashboardId` is optional.
navigate("user/:userId/dashboard(/:dashboardId)", { userId: "2" });
// ? `userId` is missing. Add one to fix the error!
navigate("user/:userId/dashboard(/:dashboardId)", { dashboardId: "2" });
// ? `oops` isn't a parameter. Remove it to fix the error!
navigate("user/:userId/dashboard(/:dashboardId)", { userId: "2", oops: ":(" });
// ???? Scroll to see how this works!
// ???? Here are the kind of things you will soon be able to do!
type ParseUrlParams<Url> =
Url extends `${infer Path}(${infer OptionalPath})`
? ParseUrlParams<Path> & Partial<ParseUrlParams<OptionalPath>>
: Url extends `${infer Start}/${infer Rest}`
? ParseUrlParams<Start> & ParseUrlParams<Rest>
: Url extends `:${infer Param}`
? { [K in Param]: string }
: {};
// navigate to a different route
function navigate<T extends string>(
path: T,
params: ParseUrlParams<T>
) {
// interpolate params
let url = Object.entries<string>(params).reduce<string>(
(path, [key, value]) => path.replace(`:${key}`, value),
path
);
// clean url
url = url.replace(/(\(|\)|\/?:[^\/]+)/g, '')
// update url
history.pushState({}, '', url);
}“TypeScript類型級別實例代碼分析”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。