Readonly TypeScript Types
A collection of readonly TypeScript types inspired by the built-in ReadonlyArray
, ReadonlyMap
, etc.
Installation
# yarn
yarn add readonly-types
# npm
npm install readonly-types
Usage
// Here's an example using ReadonlyURL.
import { ReadonlyURL } from "readonly-types";
// This is fine.
const hasFooSearchParam = (url: ReadonlyURL) => url.searchParams.has("foo");
// But this won't compile.
const setFooSearchParam = (url: ReadonlyURL) => url.searchParams.set("foo", "bar");
The Types
- ReadonlyRecord (for Record)
- ReadonlyURL (for URL)
- ReadonlyURLSearchParams (for URLSearchParams)
- ReadonlyDate (for Date)
- ReadonlyWeakSet (for WeakSet)
- ReadonlyWeakMap (for WeakMap)
- PRs welcome!
Linting
You can ban the mutable counterparts to these readonly types using ESLint, no-restricted-globals and typescript-eslint/ban-types.
rules: {
"@typescript-eslint/ban-types": [
"error",
{
types: {
Record: {
fixWith: "ReadonlyRecord",
},
URL: {
fixWith: "ReadonlyURL",
},
URLSearchParams: {
fixWith: "ReadonlyURLSearchParams",
},
Date: {
fixWith: "ReadonlyDate",
},
},
},
],
"no-restricted-globals": [
"error",
{ name: "URL" },
{ name: "URLSearchParams" },
{ name: "Date" },
],
},
These lint rules are configured by eslint-config-typed-fp for you.
See Also
- https://github.com/danielnixon/eslint-config-typed-fp
- https://github.com/immutable-js/immutable-js
- https://github.com/jonaskello/eslint-plugin-functional
- https://github.com/krzkaczor/ts-essentials#deep-partial--deep-required--deep-readonly--deep-nonnullable
- https://github.com/piotrwitek/utility-types#deepreadonlyt