Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

toDisplayString in packages/shared/src/toDisplayString.ts should use default JSON.stringify for objects without toString #4334

Closed
JamesChenX opened this issue Aug 13, 2021 · 2 comments · Fixed by #4335 or #4337
Labels
🐞 bug Something isn't working

Comments

@JamesChenX
Copy link

Version

3.2.2

Reproduction link

9d5fd33

Steps to reproduce

toDisplayString({a: 1}) will fail TypeError: Cannot convert object to primitive value

What is expected?

toDisplayString({a: 1}) should output a display string

What is actually happening?

toDisplayString({a: 1}) fails because the object doesn't have toString implementation


The bug is caused by this PR: 9d5fd33
And please take PRs seriously, especially Vue is a fundamental framework.

@edison1105
Copy link
Member

I tried it works fine and the test case passed.
Could you provide a mini repro ? I might be missing something?

@JamesChenX
Copy link
Author

JamesChenX commented Aug 14, 2021

@edison1105 Sorry about the misleading example.
I was tricked by the pitfall of Object:

Steps to reproduce

Taking the following vars as an example, toDisplayString will fail with "var", but will NOT fail with var "b".
because "val" isn't inherited from Object meaning it doesn't have toString while "b" has.
"val" works fine with JSON.stringify(val) but fails with String(val)
image

Solution

const toDisplayString = (val) => {
    return val == null
        ? ''
        : isArray(val) || (isObject(val) && (val.toString === objectToString || val.toString == null)) // Add "val.toString == null"
            ? JSON.stringify(val, replacer, 2)
            : String(val);
};

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
🐞 bug Something isn't working
Projects
None yet
4 participants
@yyx990803 @edison1105 @JamesChenX and others