-
I imagine I'm just missing something in the documentation, but I'm trying to figure out how to add TypeScript types to conditions for a non-SQL-backed, purely POJO application. I assume there's got to be some way to inform import { AbilityBuilder, type MatchConditions, PureAbility } from "@casl/ability";
type User = {id: string; blogPostIds: string[] };
type BlogPost = { id: string; title: string };
export type AppAction = "read";
export type AppSubject = BlogPost | "BlogPost";
export type AppAbility = PureAbility<[AppAction, AppSubject], MatchConditions>;
const lambdaMatcher = (matchConditions: MatchConditions) => matchConditions;
export function defineAbility(user: User): AppAbility {
const { can, build } = new AbilityBuilder<AppAbility>(PureAbility);
// blogPost = "AnyObject" in TypeScript, here, how do I convince CASL it is a BlogPost type and get property type checks?
can("read", "BlogPost", (blogPost) => user.blogPostIds.includes(blogPost.id));
return build({ conditionsMatcher: lambdaMatcher });
} |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
The example in the documentation returns TypeScript warnings/errors, likely because it doesn't appear to even attempt to define what an import {
PureAbility,
AbilityBuilder,
type AbilityTuple,
type MatchConditions,
} from "@casl/ability";
type AppAbility = PureAbility<AbilityTuple, MatchConditions>;
const lambdaMatcher = (matchConditions: MatchConditions) => matchConditions;
export default function defineAbilityFor(user: any): AppAbility {
const { can, build } = new AbilityBuilder<AppAbility>(PureAbility);
can("read", "Article", ({ authorId }) => authorId === user.id);
can("read", "Article", ({ status }) =>
["draft", "published"].includes(status),
);
return build({ conditionsMatcher: lambdaMatcher });
} |
Beta Was this translation helpful? Give feedback.
-
Please read it here https://casl.js.org/v6/en/advanced/typescript#ability-builder-type-inference |
Beta Was this translation helpful? Give feedback.
Please read it here https://casl.js.org/v6/en/advanced/typescript#ability-builder-type-inference