Skip to content

Add readonly property detection in conditional typesΒ #62280

@scrollDynasty

Description

@scrollDynasty

πŸ” Search Terms

readonly keys, mutable keys, utility type, extract readonly, readonly properties, key filtering, property keys, readonly extraction, conditional mapping

βœ… Viability Checklist

⭐ Suggestion

Add built-in support for detecting readonly properties in TypeScript's conditional types system. This would enable developers to create custom utility types that can distinguish between readonly and mutable properties.

Currently, there's no reliable way to detect if a property is readonly using TypeScript's type system. This language enhancement would enable:

  • Better type safety in state management libraries
  • Safer form handling with readonly fields
  • More precise API typing for update operations

This is not a request for new utility types, but rather a language-level improvement that would enable the community to build such utilities themselves.

πŸ“ƒ Motivating Example

With this language enhancement, developers could write:

interface User {
readonly id: string;
readonly createdAt: Date;
name: string;
email: string;
}

// Community could then create:
type ReadonlyKeys = ... // Using the new language feature
type MutableKeys = ... // Using the new language feature

// Enable safer patterns:
function updateUser(user: User, updates: OnlyMutable) {
return { ...user, ...updates };
}

πŸ’» Use Cases

1. Form Libraries

interface FormConfig {
fields: Record<MutableKeys, FieldConfig>;
// Only allow form fields for mutable properties
}

2. State Management

function createReducer(
initialState: T,
mutations: Record<string, (state: T, payload: any) => Pick<T, MutableKeys>>
) {
// Ensure reducers only update mutable fields
}

3. API Design

interface Entity {
readonly id: string;
readonly version: number;
name: string;
description: string;
}

// Auto-generate update DTOs that exclude readonly fields
type UpdateEntityDTO = Pick<Entity, MutableKeys>;
// Result: { name: string; description: string }

4. Database ORMs

class Repository {
update(id: string, data: Pick<T, MutableKeys>): Promise {
// Prevent updates to readonly fields like id, createdAt, etc.
}
}

5. Configuration Objects

interface Config {
readonly environment: 'dev' | 'prod';
readonly version: string;
debug: boolean;
apiUrl: string;
}

// Allow runtime updates only to mutable config
type RuntimeConfig = Pick<Config, MutableKeys>;

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions