When working with SharePoint as a developer you often need access to SharePoint data. If you use TypeScript you expect that all data will be strongly typed. However, it's not a case if you work with SharePoint dynamic data like lists and libraries.
Consider the code below written with PnPjs:
sp.web.lists.getByTitle('Clients').items.get()
.then((items: any[]) => {
for (const item of items) {
console.log(item);
}
});
or with SPHttpClient inside SharePoint Framework solution:
this.context.spHttpClient.get(`${currentWebUrl}/_api/web/lists/getByTitle('Clients')/items`, SPHttpClient.configurations.v1)
.then((response: SPHttpClientResponse) => {
response.json().then((items: any[]) => {
for (const item of items) {
console.log(item);
}
});
});
In both cases, you don't know the type of items beforehand and have to use any type (items: any[]). What's wrong with any type? In TypeScript it's considered as bad practice. Of course you can and should use any in some edge cases, but in general, it's considered as bad. With any type you don't have type intellisense in vscode, you lose type checking if you want to use your variable elsewhere. So how to fix it?
To fix it you should create a separate interface manually and describe all needed fields. In that case instead of any you use:
items: Client[]
While it works, it has a few drawbacks:
- you have to create all needed interfaces manually
- if you have a need to access additional fields, you will have to go and update corresponding interfaces
- if you (or team members) add a field to a list, you will have to go and update corresponding interfaces
What if there is a tool, which generates all required always up-to-date interfaces for you?
This is exactly what SharePoint Typed Item does - it takes your configuration and outputs TypeScript interfaces based on SharePoint lists, libraries and content types.
Read further to find out how to get started with SharePoint Typed Item extension. More...