diff --git a/content/02-Primitive-Types/08-Defining-Constant-Values/code.ts b/content/02-Primitive-Types/08-Defining-Constant-Values/code.ts new file mode 100644 index 0000000..4442c37 --- /dev/null +++ b/content/02-Primitive-Types/08-Defining-Constant-Values/code.ts @@ -0,0 +1,76 @@ +const code: any = { + type: "object", + properties: { + name: { + type: "string", + }, + age: {}, + companyName: {}, + }, +}; + +const solution = structuredClone(code); +solution.properties.companyName = { + const: "Postman", +}; + +solution.properties.age = { + const: 25, +}; + +const testCases: any[] = [ + { + input: { + name: "person", + age: 25, + companyName: "Postman", + }, + expected: true, + }, + { + input: { + name: "person", + age: 25, + companyName: "Google", + }, + expected: false, + }, + { + input: { + name: "person", + age: 26, + companyName: "Postman", + }, + expected: false, + }, + { + input: { + name: "person", + age: 26, + companyName: "Google", + }, + expected: false, + }, + { + input: { + name: "person", + age: 24, + companyName: "Postman", + }, + expected: false, + }, + { + input: { + name: 0, + age: 25, + companyName: "Postman", + }, + expected: false, + }, +]; + +module.exports = { + code, + solution, + testCases, +}; diff --git a/content/02-Primitive-Types/08-Defining-Constant-Values/instructions.mdx b/content/02-Primitive-Types/08-Defining-Constant-Values/instructions.mdx new file mode 100644 index 0000000..c669504 --- /dev/null +++ b/content/02-Primitive-Types/08-Defining-Constant-Values/instructions.mdx @@ -0,0 +1,43 @@ +--- +title: Defining Constant Values +description: Learn to Define constant values in JSON Schema. +keywords: const, constant, JSON Schema +--- + +# Constant Values + +So far, we have used the `enum` keyword to define a list of allowed values for a property. But **what if you want to define a single constant value for a property?** + +Consider, you want to define a property `companyName` with a constant value `Postman`. any other value for `companyName` should be considered invalid. + +```json highlightLineStart={4} +{ + "name":"John Doe", + "age": 25, + "companyName": "Postman" +} +``` + +## Const Keyword + +The `const` keyword is used to define a single constant value for a property. The value of the `const` keyword **can be any valid JSON value**. + +**Example** + +```json +{ + "const": "Postman" +} +``` + +Now, try to add a new property `companyName` in the JSON object such that it should have a constant value `Postman`. + +Just for practice, we will also **set the age to a constant value of 25**. + + + + + +- Values defined in `const` are case-sensitive. So `Postman` and `postman` are considered different values. +- You don't need to add `type` keywords when using `const`. The `const` keyword itself implies the type of the value. + \ No newline at end of file