Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

immutable string #523

Open
danielnixon opened this issue Feb 3, 2023 · 2 comments
Open

immutable string #523

danielnixon opened this issue Feb 3, 2023 · 2 comments

Comments

@danielnixon
Copy link
Collaborator

Strings are Immutable at runtime, but only (strictly speaking) ReadonlyDeep at compile time.

As so often, the cause is method syntax, in particular:

interface RelativeIndexable<T> {
    /**
     * Takes an integer value and returns the item at that index,
     * allowing for positive and negative integers.
     * Negative integers count back from the last item in the array.
     */
    at(index: number): T | undefined;
}

Observe:

const foo = "hello";

// This compiles but throws at runtime
// eslint-disable-next-line functional/no-expression-statements, functional/immutable-data, functional/functional-parameters
foo.at = () => "";

It would be nice (if extremely low priority) if this could be caught at compile time, before linting and certainly before runtime.

@danielnixon
Copy link
Collaborator Author

This trick fixes it:

export type ImmutableString = ImmutableShallow<string>;

const foo: ImmutableString = "";

// No longer compiles: Cannot assign to 'at' because it is a read-only property. ts(2540)
// eslint-disable-next-line functional/no-expression-statements, functional/immutable-data, functional/functional-parameters
foo.at = () => "";

@danielnixon
Copy link
Collaborator Author

ImmutableString would be only a novelty in practice, because:

const a: string = "";
const b: ImmutableString = a;
// Type 'ImmutableString' is not assignable to type 'string'. ts(2322)
const c: string = b;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant