Skip to content

Commit 9d5fd33

Browse files
authored
fix(shared): support custom .toString() in text interpolation again (#4210)
fix #3944
1 parent 1e3d468 commit 9d5fd33

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

packages/shared/__tests__/toDisplayString.spec.ts

+13-1
Original file line numberDiff line numberDiff line change
@@ -31,10 +31,22 @@ describe('toDisplayString', () => {
3131
})
3232
).toBe(JSON.stringify({ n: 1, np: 2 }, null, 2))
3333
})
34+
35+
test('objects with custom toString', () => {
36+
class TestClass {
37+
toString() {
38+
return 'foo'
39+
}
40+
}
41+
const instance = new TestClass()
42+
expect(toDisplayString(instance)).toBe('foo')
43+
const obj = { toString: () => 'bar' }
44+
expect(toDisplayString(obj)).toBe('bar')
45+
})
3446

3547
test('native objects', () => {
3648
const div = document.createElement('div')
37-
expect(toDisplayString(div)).toBe(`"[object HTMLDivElement]"`)
49+
expect(toDisplayString(div)).toBe('[object HTMLDivElement]')
3850
expect(toDisplayString({ div })).toMatchInlineSnapshot(`
3951
"{
4052
\\"div\\": \\"[object HTMLDivElement]\\"

packages/shared/src/toDisplayString.ts

+9-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,11 @@
1-
import { isArray, isMap, isObject, isPlainObject, isSet } from './index'
1+
import {
2+
isArray,
3+
isMap,
4+
isObject,
5+
isPlainObject,
6+
isSet,
7+
objectToString
8+
} from './index'
29

310
/**
411
* For converting {{ interpolation }} values to displayed strings.
@@ -7,7 +14,7 @@ import { isArray, isMap, isObject, isPlainObject, isSet } from './index'
714
export const toDisplayString = (val: unknown): string => {
815
return val == null
916
? ''
10-
: isObject(val)
17+
: isArray(val) || (isObject(val) && val.toString === objectToString)
1118
? JSON.stringify(val, replacer, 2)
1219
: String(val)
1320
}

0 commit comments

Comments
 (0)