Skip to content

Commit 845f593

Browse files
authored
[Codegen] Parse Record<string, T> in TypeScript TurboModule specs as a dictionary
## Summary: Fixes #59981. `@react-native/codegen`'s TypeScript parser rejects `Record<string, T>` and `Readonly<Record<string, T>>` in a TurboModule spec with `Unrecognized generic type 'Record' in NativeModule spec.` It accepts `{[key: string]: T}`, which is the same type, and parses it as a dictionary of `T`. So specs that use the idiomatic TypeScript spelling fail at `pod install` / Gradle codegen time. `translateTypeReferenceAnnotation` now handles `Record`. When the key type is `string`, it emits the same `GenericObjectTypeAnnotation` with a `dictionaryValueType` that an index signature gets. `Readonly<…>` is already unwrapped before this point. Any other `Record`, such as `Record<number, T>` or a wrong number of type arguments, fails with a new, specific error, `'Record' is only supported as Record<string, T>.`, instead of the misleading "Unrecognized generic type". The schema for `{[key: string]: T}` and `CodegenTypes.UnsafeObject` is unchanged. ## Changelog: [GENERAL] [ADDED] - Codegen: parse `Record<string, T>` in TypeScript TurboModule specs as a dictionary ## Test Plan: New tests: - e2e tests in `typescript-module-parser-e2e-test.js`, run for each parameter variant (required, optional, nullable, nullable+optional) and for nullable and non-nullable returns: - `Record<string, number>` parses to a dictionary of numbers. - `Record<string, unknown>` gives the same schema as `{[key: string]: unknown}`. - `Readonly<Record<string, Animal>>` gives a dictionary of the `Animal` alias. - `Record<number, string>` and `Record<string>` throw `UnsupportedRecordTypeParserError`. - Snapshot fixture `NATIVE_MODULE_WITH_RECORD` and failure fixture `NATIVE_MODULES_WITH_RECORD_WITH_NUMBER_KEY`. The new fixture is listed as a TS-only case in `checkModuleSnaps-test.js`. Before the fix, the 14 positive e2e cases failed with `Unrecognized generic type 'Record'`. After it: ``` yarn test packages/react-native-codegen Test Suites: 64 passed, 64 total Tests: 3174 passed, 3174 total Snapshots: 1281 passed, 1281 total yarn flow-check # Found 0 errors yarn eslint --max-warnings 0 <changed files> # clean yarn prettier --check <changed files> # clean ``` With the issue's reproducer ([YevheniiKotyrlo/react-native-codegen-record-in-module-spec](https://github.com/YevheniiKotyrlo/react-native-codegen-record-in-module-spec) at `03048b2`), run with `bash` and the local Node instead of Docker. "Before" runs the scripts unchanged against `react-native@0.90.0-nightly-20261117-c1acb2bd6`. "After" runs the same scripts with `node_modules/@react-native/codegen` replaced by a symlink to this branch's built package: | Script | Before | After | | --- | --- | --- | | `repro.sh` | exit 1: `Record<string, unknown>` and `Readonly<Record<string, unknown>>` → `UnsupportedGenericParserError: Unrecognized generic type 'Record'` | exit 0: both give `{"type":"GenericObjectTypeAnnotation","dictionaryValueType":{"type":"GenericObjectTypeAnnotation"}}`, the same as `{[key: string]: unknown}` | | `repro-array-element.sh` (`ReadonlyArray<Rule>`, where `Rule` has a `Record<string, unknown>` member) | exit 1: the array element is silently `{"type":"AnyTypeAnnotation"}` | exit 0: element is `TypeAliasTypeAnnotation` `Rule`, and `Rule.matched` is a dictionary | The `NATIVE_MODULE_WITH_RECORD` snapshot fixture includes the `ReadonlyArray<Rule>` case, so this silent fallback to `any` is covered too. End to end, with the built codegen package, on a spec like the issue's reproducer (`setOptions(options: Record<string, unknown>): void`, `getOptions(): Readonly<Record<string, number>>`, `getNames(): Readonly<Record<string, string | null>>`): - `node lib/cli/combine/combine-js-to-schema-cli.js schema.json specs/` (the script Android's `generateCodegenSchemaFromJavaScript` runs) now writes a schema with `GenericObjectTypeAnnotation` + `dictionaryValueType`, instead of failing. - `RNCodegen.generate` with `modulesAndroid`, `modulesIOS` and `modulesCxx` on that schema produces `ReadableMap` / `WritableMap` in Java and `jsi::Object` in the C++ spec. These are the same signatures that `{[key: string]: T}` produces. Not run: native builds of an app that uses such a spec. The generated code is identical to what an index-signature dictionary already produces. Differential Revision: D133012784 Pull Request resolved: #60079
1 parent 7564317 commit 845f593

7 files changed

Lines changed: 276 additions & 0 deletions

File tree

‎packages/react-native-codegen/src/parsers/consistency/__tests__/checkModuleSnaps-test.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ const tsExtraCases = [
2929
'NATIVE_MODULE_WITH_COMPLEX_ARRAY2',
3030
'NATIVE_MODULE_WITH_INTERSECTION_TYPES',
3131
'NATIVE_MODULE_WITH_NESTED_INTERFACES',
32+
'NATIVE_MODULE_WITH_RECORD',
3233
];
3334
const ignoredCases /*: Array<string> */ = [];
3435

‎packages/react-native-codegen/src/parsers/errors.js‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,16 @@ class UnsupportedObjectPropertyWithIndexerTypeAnnotationParserError extends Pars
261261
}
262262
}
263263

264+
class UnsupportedRecordTypeParserError extends ParserError {
265+
constructor(nativeModuleName: string, recordTypeAST: $FlowFixMe) {
266+
super(
267+
nativeModuleName,
268+
recordTypeAST,
269+
"'Record' is only supported as Record<string, T>.",
270+
);
271+
}
272+
}
273+
264274
class UnsupportedObjectPropertyValueTypeAnnotationParserError extends ParserError {
265275
constructor(
266276
nativeModuleName: string,
@@ -477,6 +487,7 @@ module.exports = {
477487
UnsupportedObjectPropertyWithIndexerTypeAnnotationParserError,
478488
UnsupportedObjectPropertyValueTypeAnnotationParserError,
479489
UnsupportedObjectDirectRecursivePropertyParserError,
490+
UnsupportedRecordTypeParserError,
480491
UnusedModuleInterfaceParserError,
481492
MoreThanOneModuleRegistryCallsParserError,
482493
UntypedModuleRegistryCallParserError,

‎packages/react-native-codegen/src/parsers/typescript/modules/__test_fixtures__/failures.js‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -307,6 +307,27 @@ export default TurboModuleRegistry.getEnforcing<Spec>('SampleTurboModule');
307307
308308
`;
309309

310+
const NATIVE_MODULES_WITH_RECORD_WITH_NUMBER_KEY = `
311+
/**
312+
* Copyright (c) Meta Platforms, Inc. and affiliates.
313+
*
314+
* This source code is licensed under the MIT license found in the
315+
* LICENSE file in the root directory of this source tree.
316+
*
317+
* @format
318+
*/
319+
320+
import type {TurboModule} from 'react-native';
321+
import {TurboModuleRegistry} from 'react-native';
322+
323+
export interface Spec extends TurboModule {
324+
readonly getMap: (a: Record<number, string>) => string;
325+
}
326+
327+
export default TurboModuleRegistry.getEnforcing<Spec>('SampleTurboModule');
328+
329+
`;
330+
310331
module.exports = {
311332
NATIVE_MODULES_WITH_UNNAMED_PARAMS,
312333
NATIVE_MODULES_WITH_PROMISE_WITHOUT_TYPE,
@@ -321,4 +342,5 @@ module.exports = {
321342
MAP_WITH_EXTRA_KEYS_NATIVE_MODULE,
322343
NATIVE_MODULES_WITH_ARRAY_BUFFER_IN_OBJECT_PROPERTY,
323344
NATIVE_MODULES_WITH_ARRAY_BUFFER_IN_EVENT_EMITTER,
345+
NATIVE_MODULES_WITH_RECORD_WITH_NUMBER_KEY,
324346
};

‎packages/react-native-codegen/src/parsers/typescript/modules/__test_fixtures__/fixtures.js‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1045,8 +1045,40 @@ export default TurboModuleRegistry.getEnforcing<Spec>('SampleTurboModule');
10451045
10461046
`;
10471047

1048+
const NATIVE_MODULE_WITH_RECORD = `
1049+
/**
1050+
* Copyright (c) Meta Platforms, Inc. and affiliates.
1051+
*
1052+
* This source code is licensed under the MIT license found in the
1053+
* LICENSE file in the root directory of this source tree.
1054+
*
1055+
* @format
1056+
*/
1057+
1058+
import type {TurboModule} from 'react-native';
1059+
import {TurboModuleRegistry} from 'react-native';
1060+
1061+
export type Options = Readonly<Record<string, number>>;
1062+
1063+
export interface Rule {
1064+
readonly target: string;
1065+
readonly matched: Record<string, unknown>;
1066+
}
1067+
1068+
export interface Spec extends TurboModule {
1069+
readonly setOptions: (options: Record<string, unknown>) => void;
1070+
readonly getOptions: () => Options;
1071+
readonly getNames: () => Readonly<Record<string, string | null>>;
1072+
readonly configure: (rules: ReadonlyArray<Rule>) => void;
1073+
}
1074+
1075+
export default TurboModuleRegistry.getEnforcing<Spec>('SampleTurboModule');
1076+
1077+
`;
1078+
10481079
module.exports = {
10491080
NATIVE_MODULE_WITH_ARRAY_BUFFER,
1081+
NATIVE_MODULE_WITH_RECORD,
10501082
NATIVE_MODULE_WITH_OBJECT_WITH_OBJECT_DEFINED_IN_FILE_AS_PROPERTY,
10511083
NATIVE_MODULE_WITH_ARRAY_WITH_UNION_AND_TOUPLE,
10521084
NATIVE_MODULE_WITH_ARRAY2_WITH_UNION_AND_TOUPLE,

‎packages/react-native-codegen/src/parsers/typescript/modules/__tests__/__snapshots__/typescript-module-parser-snapshot-test.js.snap‎

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ exports[`RN Codegen TypeScript Parser Fails with error message NATIVE_MODULES_WI
1818

1919
exports[`RN Codegen TypeScript Parser Fails with error message NATIVE_MODULES_WITH_PROMISE_WITHOUT_TYPE 1`] = `"Module NativeSampleTurboModule: Generic 'Promise' must have type parameters."`;
2020

21+
exports[`RN Codegen TypeScript Parser Fails with error message NATIVE_MODULES_WITH_RECORD_WITH_NUMBER_KEY 1`] = `"Module NativeSampleTurboModule: 'Record' is only supported as Record<string, T>."`;
22+
2123
exports[`RN Codegen TypeScript Parser Fails with error message NATIVE_MODULES_WITH_UNNAMED_PARAMS 1`] = `"Module NativeSampleTurboModule: All function parameters must be named."`;
2224

2325
exports[`RN Codegen TypeScript Parser Fails with error message NUMERIC_VALUES_ENUM_NATIVE_MODULE 1`] = `"Module NativeSampleTurboModule: Failed parsing the enum SomeEnum in NativeSampleTurboModule with the error: Enum values can not be mixed. They all must be either blank, number, or string values."`;
@@ -3221,6 +3223,123 @@ exports[`RN Codegen TypeScript Parser can generate fixture NATIVE_MODULE_WITH_PR
32213223
}"
32223224
`;
32233225

3226+
exports[`RN Codegen TypeScript Parser can generate fixture NATIVE_MODULE_WITH_RECORD 1`] = `
3227+
"{
3228+
'modules': {
3229+
'NativeSampleTurboModule': {
3230+
'type': 'NativeModule',
3231+
'aliasMap': {
3232+
'Rule': {
3233+
'type': 'ObjectTypeAnnotation',
3234+
'properties': [
3235+
{
3236+
'name': 'target',
3237+
'optional': false,
3238+
'typeAnnotation': {
3239+
'type': 'StringTypeAnnotation'
3240+
}
3241+
},
3242+
{
3243+
'name': 'matched',
3244+
'optional': false,
3245+
'typeAnnotation': {
3246+
'type': 'GenericObjectTypeAnnotation',
3247+
'dictionaryValueType': {
3248+
'type': 'GenericObjectTypeAnnotation'
3249+
}
3250+
}
3251+
}
3252+
]
3253+
}
3254+
},
3255+
'enumMap': {},
3256+
'spec': {
3257+
'eventEmitters': [],
3258+
'methods': [
3259+
{
3260+
'name': 'setOptions',
3261+
'optional': false,
3262+
'typeAnnotation': {
3263+
'type': 'FunctionTypeAnnotation',
3264+
'returnTypeAnnotation': {
3265+
'type': 'VoidTypeAnnotation'
3266+
},
3267+
'params': [
3268+
{
3269+
'name': 'options',
3270+
'optional': false,
3271+
'typeAnnotation': {
3272+
'type': 'GenericObjectTypeAnnotation',
3273+
'dictionaryValueType': {
3274+
'type': 'GenericObjectTypeAnnotation'
3275+
}
3276+
}
3277+
}
3278+
]
3279+
}
3280+
},
3281+
{
3282+
'name': 'getOptions',
3283+
'optional': false,
3284+
'typeAnnotation': {
3285+
'type': 'FunctionTypeAnnotation',
3286+
'returnTypeAnnotation': {
3287+
'type': 'GenericObjectTypeAnnotation',
3288+
'dictionaryValueType': {
3289+
'type': 'NumberTypeAnnotation'
3290+
}
3291+
},
3292+
'params': []
3293+
}
3294+
},
3295+
{
3296+
'name': 'getNames',
3297+
'optional': false,
3298+
'typeAnnotation': {
3299+
'type': 'FunctionTypeAnnotation',
3300+
'returnTypeAnnotation': {
3301+
'type': 'GenericObjectTypeAnnotation',
3302+
'dictionaryValueType': {
3303+
'type': 'NullableTypeAnnotation',
3304+
'typeAnnotation': {
3305+
'type': 'StringTypeAnnotation'
3306+
}
3307+
}
3308+
},
3309+
'params': []
3310+
}
3311+
},
3312+
{
3313+
'name': 'configure',
3314+
'optional': false,
3315+
'typeAnnotation': {
3316+
'type': 'FunctionTypeAnnotation',
3317+
'returnTypeAnnotation': {
3318+
'type': 'VoidTypeAnnotation'
3319+
},
3320+
'params': [
3321+
{
3322+
'name': 'rules',
3323+
'optional': false,
3324+
'typeAnnotation': {
3325+
'type': 'ArrayTypeAnnotation',
3326+
'elementType': {
3327+
'type': 'TypeAliasTypeAnnotation',
3328+
'name': 'Rule'
3329+
}
3330+
}
3331+
}
3332+
]
3333+
}
3334+
}
3335+
]
3336+
},
3337+
'moduleName': 'SampleTurboModule'
3338+
}
3339+
}
3340+
}"
3341+
`;
3342+
32243343
exports[`RN Codegen TypeScript Parser can generate fixture NATIVE_MODULE_WITH_ROOT_TAG 1`] = `
32253344
"{
32263345
'modules': {

‎packages/react-native-codegen/src/parsers/typescript/modules/__tests__/typescript-module-parser-e2e-test.js‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ const {
1919
MissingTypeParameterGenericParserError,
2020
UnnamedFunctionParamParserError,
2121
UnsupportedGenericParserError,
22+
UnsupportedRecordTypeParserError,
2223
UnsupportedTypeAnnotationParserError,
2324
} = require('../../../errors');
2425
const {unwrapNullable} = require('../../../parsers-commons');
@@ -268,6 +269,60 @@ describe('TypeScript Module Parser', () => {
268269
);
269270
});
270271

272+
describe('Record Types', () => {
273+
it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter of type 'Record<string, number>' as a dictionary`, () => {
274+
const [paramTypeAnnotation] = parseParamType(
275+
'arg',
276+
'Record<string, number>',
277+
);
278+
expect(paramTypeAnnotation).toEqual({
279+
type: 'GenericObjectTypeAnnotation',
280+
dictionaryValueType: {type: 'NumberTypeAnnotation'},
281+
});
282+
});
283+
284+
it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter of type 'Record<string, T>' as the same schema as '{[key: string]: T}'`, () => {
285+
const [recordTypeAnnotation] = parseParamType(
286+
'arg',
287+
'Record<string, unknown>',
288+
);
289+
const [indexSignatureTypeAnnotation] = parseParamType(
290+
'arg',
291+
'{[key: string]: unknown}',
292+
);
293+
expect(recordTypeAnnotation).toEqual(
294+
indexSignatureTypeAnnotation,
295+
);
296+
});
297+
298+
it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter of type 'Readonly<Record<string, Animal>>'`, () => {
299+
const [paramTypeAnnotation, module] = parseParamType(
300+
'arg',
301+
'Readonly<Record<string, Animal>>',
302+
);
303+
expect(paramTypeAnnotation).toEqual({
304+
type: 'GenericObjectTypeAnnotation',
305+
dictionaryValueType: {
306+
type: 'TypeAliasTypeAnnotation',
307+
name: 'Animal',
308+
},
309+
});
310+
expectAnimalTypeAliasToExist(module);
311+
});
312+
313+
it(`should not parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter of type 'Record<number, string>'`, () => {
314+
expect(() =>
315+
parseParamType('arg', 'Record<number, string>'),
316+
).toThrow(UnsupportedRecordTypeParserError);
317+
});
318+
319+
it(`should not parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter of type 'Record' without two type arguments`, () => {
320+
expect(() => parseParamType('arg', 'Record<string>')).toThrow(
321+
UnsupportedRecordTypeParserError,
322+
);
323+
});
324+
});
325+
271326
describe('Reserved Types', () => {
272327
RESERVED_FUNCTION_VALUE_TYPE_NAME.forEach(FLOW_TYPE => {
273328
it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter of reserved type '${FLOW_TYPE}'`, () => {
@@ -979,6 +1034,16 @@ describe('TypeScript Module Parser', () => {
9791034
);
9801035
});
9811036

1037+
it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return of type 'Readonly<Record<string, string>>' as a dictionary`, () => {
1038+
const [returnTypeAnnotation] = parseReturnType(
1039+
'Readonly<Record<string, string>>',
1040+
);
1041+
expect(returnTypeAnnotation).toEqual({
1042+
type: 'GenericObjectTypeAnnotation',
1043+
dictionaryValueType: {type: 'StringTypeAnnotation'},
1044+
});
1045+
});
1046+
9821047
describe('Object Literals Types', () => {
9831048
// TODO: Inexact vs exact object literals?
9841049

‎packages/react-native-codegen/src/parsers/typescript/modules/index.js‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ const {
2929
UnsupportedEnumDeclarationParserError,
3030
UnsupportedGenericParserError,
3131
UnsupportedObjectPropertyWithIndexerTypeAnnotationParserError,
32+
UnsupportedRecordTypeParserError,
3233
UnsupportedTypeAnnotationParserError,
3334
} = require('../../errors');
3435
const {parseObjectProperty} = require('../../parsers-commons');
@@ -47,6 +48,7 @@ const {
4748
typeAliasResolution,
4849
typeEnumResolution,
4950
} = require('../../parsers-primitives');
51+
const {getTypeArguments} = require('../../utils');
5052
const {flattenProperties} = require('../components/componentsUtils');
5153
const {flattenIntersectionType} = require('../parseTopLevelType');
5254

@@ -156,6 +158,30 @@ function translateTypeReferenceAnnotation(
156158
translateTypeAnnotation,
157159
);
158160
}
161+
case 'Record': {
162+
// Record<string, T> is a dictionary, like {[key: string]: T}
163+
const typeArguments = getTypeArguments(typeAnnotation)?.params ?? [];
164+
if (
165+
typeArguments.length !== 2 ||
166+
typeArguments[0].type !== 'TSStringKeyword'
167+
) {
168+
throw new UnsupportedRecordTypeParserError(
169+
hasteModuleName,
170+
typeAnnotation,
171+
);
172+
}
173+
const valueType = translateTypeAnnotation(
174+
hasteModuleName,
175+
typeArguments[1],
176+
types,
177+
aliasMap,
178+
enumMap,
179+
tryParse,
180+
cxxOnly,
181+
parser,
182+
);
183+
return emitDictionary(nullable, valueType);
184+
}
159185
default: {
160186
const commonType = emitCommonTypes(
161187
hasteModuleName,

0 commit comments

Comments
 (0)