| 1 | /** |
| 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | * |
| 4 | * This source code is licensed under the MIT license found in the |
| 5 | * LICENSE file in the root directory of this source tree. |
| 6 | * |
| 7 | * @flow |
| 8 | */ |
| 9 | |
| 10 | import {checkFormFieldValueStringCoercion} from 'shared/CheckStringCoercion'; |
| 11 | |
| 12 | export opaque type ToStringValue = |
| 13 | | boolean |
| 14 | | number |
| 15 | | bigint |
| 16 | | Object |
| 17 | | string |
| 18 | | null |
| 19 | | void; |
| 20 | |
| 21 | // Flow does not allow string concatenation of most non-string types. To work |
| 22 | // around this limitation, we use an opaque type that can only be obtained by |
| 23 | // passing the value through getToStringValue first. |
| 24 | export function toString(value: ToStringValue): string { |
| 25 | // The coercion safety check is performed in getToStringValue(). |
| 26 | // eslint-disable-next-line react-internal/safe-string-coercion |
| 27 | return '' + (value as any); |
| 28 | } |
| 29 | |
| 30 | export function getToStringValue(value: mixed): ToStringValue { |
| 31 | switch (typeof value) { |
| 32 | case 'bigint': |
| 33 | case 'boolean': |
| 34 | case 'number': |
| 35 | case 'string': |
| 36 | case 'undefined': |
| 37 | return value; |
| 38 | case 'object': |
| 39 | if (__DEV__) { |
| 40 | checkFormFieldValueStringCoercion(value); |
| 41 | } |
| 42 | return value; |
| 43 | default: |
| 44 | // function, symbol are assigned as empty strings |
| 45 | return ''; |
| 46 | } |
| 47 | } |