[removed] Different return types

后端 未结 3 596
余生分开走
余生分开走 2021-01-18 01:20

I saw I could return different types from the same function in JavaScript. Is this practice idiomatic or should it be discouraged?

For example:

somef         


        
3条回答
  •  旧巷少年郎
    2021-01-18 02:05

    I would discourage it. Any code that uses a function that can return different types depending on the context will have to check the returned value.

    There are situations where it makes sense, however. Say you have a function that parses a string, for example JSON. In that situation it makes a whole lot of sense to return arrays if the input string is a JSON string representing an array, an object if the input contains an object, a boolean, a number, etc.

    In general, do the thing that would cause the least surprise. Your example would surprise me a lot, for example.

提交回复
热议问题