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

fix: make typings more accurate by avoiding explict cast on consts #2475

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

kpanot
Copy link
Contributor

@kpanot kpanot commented Nov 15, 2024

Proposed change

When creating an object that is intended to be read-only, we should let typescript infer the type.

Not good:

interface NamedObjectMaybe {
  name?: string;
}
const UNMOVABLE_OBJECT: NamedObjectMaybe = {
  name: 'unicorn'
};

// UNMOVABLE_OBJECT.name is typed as string | undefined

Nice:

interface NamedObjectMaybe {
  name?: string;
}
const UNMOVABLE_OBJECT = {
  name: 'unicorn'
} as const satisfies NamedObjectMaybe;

// UNMOVABLE_OBJECT.name is typed as 'unicorn' but we still validate that UNMOVABLE_OBJECT matches the interface

Related issues

@kpanot kpanot requested a review from a team as a code owner November 15, 2024 08:22
fpaul-1A
fpaul-1A previously approved these changes Nov 15, 2024
sdo-1A
sdo-1A previously approved these changes Nov 15, 2024
mrednic-1A
mrednic-1A previously approved these changes Nov 15, 2024
@matthieu-crouzet
Copy link
Contributor

matthieu-crouzet commented Nov 15, 2024

@kpanot kpanot dismissed stale reviews from mrednic-1A, sdo-1A, and fpaul-1A via 89cdb57 November 29, 2024 01:42
@kpanot kpanot force-pushed the chore/more-precise-typings branch 2 times, most recently from 89cdb57 to c374215 Compare November 29, 2024 06:56
fpaul-1A
fpaul-1A previously approved these changes Nov 29, 2024
@@ -44,12 +44,12 @@ import {
} from './event-track.configuration';

/** The initial value of the performance measurements */
export const performanceMarksInitialState: PerfEventPayload = {
export const performanceMarksInitialState: Readonly<PerfEventPayload> = {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we put Readonly on some but not on all of the as const ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure I got the question :S.
readonly<...> is mandatory when the constant is declared as const but, as it is exposed, should also have an explicit type following an interface.
When there are not exported, it does not need to have the type defined but only to satisfy it. So no need Readonly<...>.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment