I am using PnP JS in SPFx to get page content. I wanted to get content type id of the page and check if it belongs to certain content type.

I can't seem to make contain or includes function work so I have been trying to use substring to get first 44 character out so I can use it to compare but I am getting error:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'substring')

import { sp } from "@pnp/sp/presets/all";

public onInit(): Promise<void> {
      spfxContext: this.context
    let content:string=d.contentTypeId
    let sitecontentid:string= "0x01100912345D1CB255DA76424F860D91F20E6C4118000B8757F9909754BBB035517811AE70E"
    let contentid:string= content.substring(0,43)

    if  (contentid==sitecontent)
        do something

    return Promise.resolve();

1 Answer 1


Use below code inside .then() function:

let contentTypeIdString:string = d.ContentTypeId;
let siteContentTypeId:string = "0x01100912345D1CB255DA76424F860D91F20E6C4118000B8757F9909754BBB035517811AE70E";

let contentTypeId:string = contentTypeIdString ? contentTypeIdString.substring(0, 43): "";

if  (contentTypeId == siteContentTypeId){
    //Your code
    console.log("Content Type Id matched.");
} else {
    console.log("Content Type Id does not match.");
  • It has fixed the error but it isn't bringing back any value. Is this because I have to add in await?
    – hellothere
    Nov 5, 2021 at 12:13
  • What data are you getting in d variable? Nov 5, 2021 at 13:04
  • I can see in the log that it is bringing back ContentTypeId: "0x0101009D1CB255DA76424F860D91F20E6C4118000B5BA1CF9909754BBB035517811AE70E0069911E447514314B86BB32EBE555E9EC" but I have put alert that displays the value after let contentTypeId:string = contentTypeIdString ? contentTypeIdString.substring(0, 43): ""; and it just comes up blank.
    – hellothere
    Nov 5, 2021 at 13:26
  • Above code should work for you for this response. I see above content type id does not match with your siteContentTypeId. So, it will not execute if block. Try using updated code in my answer OR adding breakpoint at the line let contentTypeId:string = & see if brings the response correctly. Nov 5, 2021 at 13:34
  • Thanks,@ganesh-sanap it is working now. I had let content:string=d.contentTypeId the C in contentTypeId should have been capital. Thanks for your help :)
    – hellothere
    Nov 5, 2021 at 14:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.