mirror of
https://github.com/facebook/react-native.git
synced 2026-11-18 20:19:07 +00:00
Fix TS exactOptionalPropertyTypes compatibility for generated types (#57628)
Summary: Pull Request resolved: https://github.com/react/react-native/pull/57628 NOTE: Patches over a `flow-api-translator` bug, which I'll fix upstream later. We need to pick this to `0.87-stable` to resolve user integration issues. **Context** TypeScript's `exactOptionalPropertyTypes` flag (strict mode) creates a distinction between `foo?: T` and `foo?: T | undefined`. ```js // Flow's semantics interface Props { onRefresh?: () => void; } const a: Props = { onRefresh: undefined }; // ✅ ok ``` ```ts // TypeScript with exactOptionalPropertyTypes: true (i.e. strict mode) interface Props { onRefresh?: () => void; } const a: Props = { onRefresh: undefined }; // ❌ error interface PropsFixed { onRefresh?: (() => void) | undefined; } const b: PropsFixed = { onRefresh: undefined }; // ✅ ok ``` With this added strictness in TypeScript, our generated types via `flow-api-translator` could create downstream type incompatibility in apps. **This diff** Patches the above issue in React Native's Flow → TS `types_generated/` pipeline. We transform all instances to the wider `foo?: T | undefined` format, for maximum compatibility. **Notes** `foo?: T [| undefined]` **remains stripped** in the API snapshot (existing transform with the aim of a concise format). There is a net, nonfunctional snapshot diff around function members, which (as a positive result) are re-ordered. Changelog: [General][Fixed] - **Strict TypeScript API**: Optional property types are now widened to explicitly include `| undefined` for `exactOptionalPropertyTypes` compatibility Reviewed By: cipolleschi Differential Revision: D113030161 fbshipit-source-id: 3ab005edab6b80b18fbb9ae7125ba56e3bd94195
This commit is contained in:
1 parent
fcac53fe87
commit
0fc76bb527
6 files changed
+317
-148
No files matched your search
+65
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict-local
|
||||
* @format
|
||||
*/
|
||||
|
||||
const ensureUndefinedOnOptionalMembersVisitor = require('../ensureUndefinedOnOptionalMembers.js');
|
||||
const babel = require('@babel/core');
|
||||
|
||||
async function translate(code: string): Promise<string> {
|
||||
const result = await babel.transformAsync(code, {
|
||||
plugins: [
|
||||
'@babel/plugin-syntax-typescript',
|
||||
ensureUndefinedOnOptionalMembersVisitor,
|
||||
],
|
||||
});
|
||||
|
||||
return result.code;
|
||||
}
|
||||
|
||||
describe('ensureUndefinedOnOptionalMembers', () => {
|
||||
test('should add undefined to optional type members', async () => {
|
||||
const code = `
|
||||
type Foo = {
|
||||
a?: number,
|
||||
'b-key'?: number | string,
|
||||
c?: () => void,
|
||||
d: boolean,
|
||||
e: string | undefined,
|
||||
f?: (() => void) | number,
|
||||
};
|
||||
`;
|
||||
const result = await translate(code);
|
||||
expect(result).toMatchInlineSnapshot(`
|
||||
"type Foo = {
|
||||
a?: number | undefined;
|
||||
'b-key'?: number | string | undefined;
|
||||
c?: (() => void) | undefined;
|
||||
d: boolean;
|
||||
e: string | undefined;
|
||||
f?: (() => void) | number | undefined;
|
||||
};"
|
||||
`);
|
||||
});
|
||||
|
||||
test('should not add undefined when already present', async () => {
|
||||
const code = `
|
||||
type Foo = {
|
||||
a?: number | undefined,
|
||||
b?: undefined,
|
||||
};
|
||||
`;
|
||||
const result = await translate(code);
|
||||
expect(result).toMatchInlineSnapshot(`
|
||||
"type Foo = {
|
||||
a?: number | undefined;
|
||||
b?: undefined;
|
||||
};"
|
||||
`);
|
||||
});
|
||||
});
|
||||
+16
@@ -42,4 +42,20 @@ describe('removeUndefinedFromOptionalMembers', () => {
|
||||
};"
|
||||
`);
|
||||
});
|
||||
|
||||
test('should unwrap the lone remaining constituent, dropping redundant parens', async () => {
|
||||
const code = `
|
||||
type Foo = {
|
||||
a?: (() => void) | undefined,
|
||||
b?: number | string | undefined,
|
||||
};
|
||||
`;
|
||||
const result = await translate(code);
|
||||
expect(result).toMatchInlineSnapshot(`
|
||||
"type Foo = {
|
||||
a?: () => void;
|
||||
b?: number | string;
|
||||
};"
|
||||
`);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict-local
|
||||
* @format
|
||||
*/
|
||||
|
||||
import type {PluginObj} from '@babel/core';
|
||||
|
||||
import * as t from '@babel/types';
|
||||
|
||||
/**
|
||||
* Ensures optional object members carry an explicit `| undefined`, e.g.
|
||||
* `foo?: number` becomes `foo?: number | undefined` (members that already
|
||||
* include `undefined` are left unchanged).
|
||||
*
|
||||
* This is the format required by TypeScript consumers building with
|
||||
* `exactOptionalPropertyTypes`, under which `foo?: T` and `foo?: T | undefined`
|
||||
* are distinct. It applies to the per-module generated types; the API snapshot
|
||||
* pipeline still strips it back via `removeUndefinedFromOptionalMembers`.
|
||||
*
|
||||
* This lives in React Native as a stopgap: flow-api-translator does not yet emit
|
||||
* this format, and the generated types cannot wait for its next release.
|
||||
*
|
||||
* The API snapshot resets this via `removeUndefinedFromOptionalMembers`, which
|
||||
* also unwraps the resulting single-constituent unions so function-valued
|
||||
* members remain bare function types for `sortProperties` to group.
|
||||
*/
|
||||
const visitor: PluginObj<unknown> = {
|
||||
visitor: {
|
||||
TSPropertySignature(path) {
|
||||
if (path.node.optional !== true) {
|
||||
return;
|
||||
}
|
||||
|
||||
const typeAnnotation = path.node.typeAnnotation;
|
||||
if (!typeAnnotation || !t.isTSTypeAnnotation(typeAnnotation)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const actualTypeAnnotation = typeAnnotation.typeAnnotation;
|
||||
|
||||
if (t.isTSUndefinedKeyword(actualTypeAnnotation)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (t.isTSUnionType(actualTypeAnnotation)) {
|
||||
if (
|
||||
actualTypeAnnotation.types.some(type => t.isTSUndefinedKeyword(type))
|
||||
) {
|
||||
return;
|
||||
}
|
||||
typeAnnotation.typeAnnotation = t.tsUnionType([
|
||||
...actualTypeAnnotation.types,
|
||||
t.tsUndefinedKeyword(),
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
typeAnnotation.typeAnnotation = t.tsUnionType([
|
||||
actualTypeAnnotation,
|
||||
t.tsUndefinedKeyword(),
|
||||
]);
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = visitor;
|
||||
+19
-3
@@ -29,11 +29,27 @@ const visitor: PluginObj<unknown> = {
|
||||
return;
|
||||
}
|
||||
|
||||
const newTypeAnnotation = t.cloneDeep(actualTypeAnnotation);
|
||||
newTypeAnnotation.types = newTypeAnnotation.types.filter(
|
||||
const remainingTypes = actualTypeAnnotation.types.filter(
|
||||
type => t.isTSUndefinedKeyword(type) === false,
|
||||
);
|
||||
typeAnnotation.typeAnnotation = newTypeAnnotation;
|
||||
if (remainingTypes.length === actualTypeAnnotation.types.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Unwrap to the bare type when a single constituent remains, otherwise a
|
||||
// wrapper node survives that prints identically but breaks downstream
|
||||
// transforms (e.g. `sortProperties`) that key on the node type. The lone
|
||||
// constituent may be parenthesized (a function type inside a union needs
|
||||
// parens, e.g. `(() => void) | undefined`); those parens are redundant
|
||||
// once it is no longer part of a union.
|
||||
if (remainingTypes.length === 1) {
|
||||
const [remaining] = remainingTypes;
|
||||
typeAnnotation.typeAnnotation = t.isTSParenthesizedType(remaining)
|
||||
? remaining.typeAnnotation
|
||||
: remaining;
|
||||
} else {
|
||||
typeAnnotation.typeAnnotation = t.tsUnionType(remainingTypes);
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -30,6 +30,7 @@ const preTransforms: Array<PreTransformFn> = [
|
||||
];
|
||||
const postTransforms = (filePath: string): Array<PluginObj<unknown>> => [
|
||||
require('./transforms/typescript/convertTypeAliasesToInterfaces'),
|
||||
require('./transforms/typescript/ensureUndefinedOnOptionalMembers'),
|
||||
require('./transforms/typescript/replaceProtectedConstructors'),
|
||||
require('./transforms/typescript/replaceDefaultExportName')(filePath),
|
||||
];
|
||||
|
||||
Reference in new issue
Block a user