From fa2943a1d885963e618e32c33fa5c40b9a6e80fa Mon Sep 17 00:00:00 2001 From: Egor Blinov Date: Sat, 29 Jun 2024 12:56:15 +0200 Subject: [PATCH] fix(isolated_declarations): inferring literal types for readonly class fileds --- crates/oxc_isolated_declarations/src/class.rs | 9 ++++++++- .../tests/fixtures/class.ts | 13 +++++++++++-- .../tests/snapshots/class.snap | 4 ++++ 3 files changed, 23 insertions(+), 3 deletions(-) diff --git a/crates/oxc_isolated_declarations/src/class.rs b/crates/oxc_isolated_declarations/src/class.rs index 6e668808d15b3..0316624b8194e 100644 --- a/crates/oxc_isolated_declarations/src/class.rs +++ b/crates/oxc_isolated_declarations/src/class.rs @@ -66,7 +66,11 @@ impl<'a> IsolatedDeclarations<'a> { .value .as_ref() .and_then(|expr| { - let ts_type = self.infer_type_from_expression(expr); + let ts_type = if property.readonly { + self.transform_expression_to_ts_type(expr) + } else { + self.infer_type_from_expression(expr) + }; if ts_type.is_none() { self.error(property_must_have_explicit_type(property.key.span())); } @@ -76,6 +80,9 @@ impl<'a> IsolatedDeclarations<'a> { }) }; + // TODO if inferred type_annotations is TSLiteral, it should stand as value, + // so `field = 'string'` remain `field = 'string'` instead of `field: 'string'` + self.ast.class_property( property.r#type, property.span, diff --git a/crates/oxc_isolated_declarations/tests/fixtures/class.ts b/crates/oxc_isolated_declarations/tests/fixtures/class.ts index f0f9579b28cc5..e5a4f40ddea25 100644 --- a/crates/oxc_isolated_declarations/tests/fixtures/class.ts +++ b/crates/oxc_isolated_declarations/tests/fixtures/class.ts @@ -6,10 +6,19 @@ export class Bar { public constructor(a: number = 0) {} } -export class Zoo { foo(f: F): F { return f } } +export class Zoo { + foo(f: F): F { + return f; + } +} export abstract class Qux { abstract foo(): void; bar(): void {} baz(): void {} -} \ No newline at end of file +} + +export class Baz { + readonly prop1 = 'some string'; + prop2 = 'another string'; +} diff --git a/crates/oxc_isolated_declarations/tests/snapshots/class.snap b/crates/oxc_isolated_declarations/tests/snapshots/class.snap index e0815c35192ab..2a754eedce393 100644 --- a/crates/oxc_isolated_declarations/tests/snapshots/class.snap +++ b/crates/oxc_isolated_declarations/tests/snapshots/class.snap @@ -18,3 +18,7 @@ export declare abstract class Qux { bar(): void; baz(): void; } +export declare class Baz { + readonly prop1: 'some string'; + prop2: string; +}