Add the ability to JSON.parse function to specify the return type, I already opened a PR #30219, implementing this feature
let parsedObj = JSON.parse<TypeObj>("{ prop: 'val' }"); // parsedObj is TypeObj
is way better than
let parsedObj = JSON.parse("{ prop: 'val' }"); // parsedObj is any
that said in the use cases ¯_(ツ)_/¯
My suggestion meets these guidelines:
While JSON.parse returns any, you can simply do
let parsedObj: Interface = JSON.parse("{ prop: 'val' }"); // parsedObj is any
So there will be no difference between adding generic type to JSON.parse and mine "solution"
@hejkerooo here's a real-world example
export const getCurrentUserDataAsync = () => SecureStore.getItemAsync(SESSION_KEY).then(data => data ? JSON.parse<LoginData>(data) : undefined);
How can your solution solve it?
type ReturnType = LoginData | undefined;
export const getCurrentUserDataAsync = (): ReturnType => SecureStore.getItemAsync(SESSION_KEY).then(data => data ? JSON.parse(data) : undefined);
But you shouldn't return undefined, consider throwing an error or try nullable pattern
Nullable pattern
edit
You should not declare return type basic on what is function returning, but function declaration itself
@hejkerooo so, for a service file that contains about ten methods like this one I'm going to define ten types separately!!!
I think this is what a type assertion is for.
JSON.parse(data) as LoginData
// or: <LoginData>JSON.parse(data)
@hejkerooo so, for a service file that contains about ten methods like this one I'm going to define ten types separately!!!
I think, this is a point of strongly typed languages
Already discussed and rejected as Working as intended: #26993 and #26994.
JSON.parse<TypeObj>("{ prop: 'val' }");
There's already a place to put that:
<TypeObj>JSON.parse("{ prop: 'val' }");
@RyanCavanaugh you're right 😅
Most helpful comment
There's already a place to put that: