MCPcopy Index your code
hub / github.com/formatjs/formatjs / ToPrimitive

Function ToPrimitive

packages/ecma262-abstract/ToPrimitive.ts:39–70  ·  view source on GitHub ↗
(input: any, preferredType: T)

Source from the content-addressed store, hash-verified

37 * https://tc39.es/ecma262/#sec-toprimitive
38 */
39export function ToPrimitive<
40 T extends 'string' | 'number' = 'string' | 'number',
41>(input: any, preferredType: T): string | number | boolean | undefined | null {
42 if (typeof input === 'object' && input != null) {
43 const exoticToPrim =
44 Symbol.toPrimitive in input ? input[Symbol.toPrimitive] : undefined
45 let hint
46 if (exoticToPrim !== undefined) {
47 if (preferredType === undefined) {
48 hint = 'default'
49 } else if (preferredType === 'string') {
50 hint = 'string'
51 } else {
52 invariant(
53 preferredType === 'number',
54 'preferredType must be "string" or "number"'
55 )
56 hint = 'number'
57 }
58 let result = exoticToPrim.call(input, hint)
59 if (typeof result !== 'object') {
60 return result
61 }
62 throw new TypeError('Cannot convert exotic object to primitive.')
63 }
64 if (preferredType === undefined) {
65 preferredType = 'number' as T
66 }
67 return OrdinaryToPrimitive(input, preferredType)
68 }
69 return input
70}

Callers 2

ToIntlMathematicalValueFunction · 0.85
ToNumberFunction · 0.85

Calls 2

OrdinaryToPrimitiveFunction · 0.85
invariantFunction · 0.70

Tested by

no test coverage detected