5

I'm trying to use useSelect with TypeScript to get the current post type. In regular JavaScript, this code works fine (and is in fact code used in the main Gutenberg repo):

const postType = useSelect(
    ( select ) => select( 'core/editor' ).getCurrentPostType(),
    []
);

However, when I convert to TypeScript, this throws a type error:

Property 'getCurrentPostType' does not exist on type 'never'.ts(2339)

I can't see what's causing it, why the return type is <never>.

The code actually does work and compiles fine, but I would like to get it type safe. Any ideas on how I can resolve this would be much appreciated.

1
  • Which version are you using? It seems like similar issue to Gutenberg issue #48133 depending on version. Commented Aug 21, 2023 at 3:13

2 Answers 2

3

You can import store from "@wordpress/editor" and use it instead of the store's name.

Additionally, you will have to import the store's selectors manually (because of a bug in the types of @wordpress/editor / @wordpress/data) like import StoreSelectors from "@wordpress/editor/store/selectors".

Example:

import {useSelect} from "@wordpress/data"
import {store as CoreEditorStore} from "@wordpress/editor"
import CoreEditorStoreSelectors from "@wordpress/editor/store/selectors"

/* ... */

const postType = useSelect(
    (select) => (
      (select(CoreEditorStore) as typeof CoreEditorStoreSelectors)
        .getCurrentPostType()
    ),
    [],
)

/* ... */

From the sources:

/*
 * (...)
 * @param storeNameOrDescriptor The store descriptor. The legacy calling convention
 *                              of passing the store name is also supported.
 * (...)
 */
Sign up to request clarification or add additional context in comments.

1 Comment

Is this still accurate? I'm struggling with my setup to get the types sorted out. Property 'getCurrentPost' does not exist on type 'never'.
0

As mentioned by @zoku, you can import the correct type and use that instead of "core/editor" in the select.

The simpler solution I've been using is just to create a very simple inline type:

interface HasCurrentPostType {
    getCurrentPostType: () => string;
};

const postType = useSelect(
    ( select ) => (select( 'core/editor' ) as HasCurrentPostType).getCurrentPostType(),
    []
);

Both are valid approaches – @zoku's is more complete in terms of using type safety from WordPress itself.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.