I do a REST request and get back JSON. Assume recent versions of Angular/TS.
What is 'best practice' here:
- Do nothing with the received JSON in terms of Types and just treat it as 'any' and put its data in the destination object(s).
const localTypedObj: UserData;
localTypedObj.userId = dataFromRestReq.userId
- Give the incoming JSON a type/name and then use that:
type NewTypeName = typeof dataFromRestReq;
const newlyTypedData: NewTypeName = dataFromRestReq;
localTypeObj.userId = newlyTypedData.userId; // Here the editor knows that userId is a thing!
- Create a Type/Interface to then apply to the incoming data:
interface NewTypeName {
userId: string;
}
// elsewhere...
let newlyTypedData = <NewTypeName>dataFromRestReq;
- Other?
Am I restricting things too much here, if an extra item is added to the JSON by back-end folks, will front-end crash if the type is expecting a certain format?