#Warn on property if another property exists?

2 messages · Page 1 of 1 (latest)

mental compass
#

In my type I have a path but I wanted typescript to warn if I have files and folderpath properties that path shouldn't be in the object. I tried to do it this way but it didn't work

declare global {
    type BaseThemeAsset = {
        key: string;
        path: string;
        size?: { width: number; height: number };
        addToScene?: boolean;
        preloadHandler?: (scene: GameScene) => void;
        createHandler?: (scene: GameScene) => void;
    };

    type ThemeAssetWithMultipleFiles = Omit<BaseThemeAsset, "path"> & {
        folderPath: string;
        files: string[];
    };

    type ThemeAssetWithCoords = BaseThemeAsset & {
        coords: { x: number; y: number };
        type: "atlas" | "sprite" | "image" | "tilesprite";
    };

    type ThemeAssetAudio = BaseThemeAsset & {
        type: "audio";
    };

    type ThemeAsset = ThemeAssetWithCoords | ThemeAssetAudio;
}

Object literal may only specify known properties, and 'folderPath' does not exist in type 'ThemeAssetWithCoords'

I think it jumps over typing the object as ThemeAssetWithMultipleFile and sets it as ThemeAssetWithCoords 🤔 .. just a guess from a ts newbie

mental compass
#
type BaseThemeAsset = {
    key: string;
    size?: { width: number; height: number };
    addToScene?: boolean;
    preloadHandler?: (scene: GameScene) => void;
    createHandler?: (scene: GameScene) => void;
} & (
    | {
          path: string;
      }
    | {
          folderPath: string;
          files: string[];
      }
);

it doesn't work the way i expected though and allows all three properties to exist