An experimental setup for tracking mutations at TypeScript compile-time
npm install ts-mutable-typebash
npm install ts-mutable-type
`
🚀 Usage
The following are the types defined by the ts-mutable-type module:
- Create
Wraps a value T in a mutable container whose state can be tracked at the type level.
- Current
Extracts the type of the current static value of a mutable type T.
- Mutate
Used in a mutating function's return type declaration as a type to which the argument is asserted (asserts arg is Mutate)
- Mutable
The base type for a type-level mutable value of type T
$3
#### Define:
`ts
type Not = A extends true ? false : true;
function create(value: T): Create {
return { runtimeValue: value } as any;
}
function toggle>(
value: T
// @ts-ignore
): asserts value is Mutate>> {
(value as any).runtimeValue = !(value as any).runtimeValue;
}
function get>(value: T): Current {
return (value as any).runtimeValue;
}
`
#### Use:
`ts
const booleanValue = create(false);
toggle(booleanValue);
const a = get(booleanValue); // true inferred at compile-time
toggle(booleanValue);
const b = get(booleanValue); // false inferred at compile-time
`
$3
#### Define:
`ts
declare const wasFunctionCalledSymbol: unique symbol;
type Ctx = {
[wasFunctionCalledSymbol]: boolean;
};
type OptionalArgsError = Current extends {
[wasFunctionCalledSymbol]: true;
}
? ['Error: this function can be called only once']
: [];
function allowOneCall>(
ctx: T,
...error: OptionalArgsError
// @ts-ignore
): asserts ctx is Mutate {
// implementation
}
declare const globalContext: Create<{ [wasFunctionCalledSymbol]: false }>;
`
#### Use:
`ts
// ✅ First call
allowOneCall(globalContext);
// ❌ Second call — compile-time error
allowOneCall(globalContext);
``