0

Can I create a type which allows only arrays where an object has a unique value in a key.

So this is okay:

[{ a: 1 }, { a: 2 }, { a: 3 }] // ✅
[{ a: true }, { a: "nice" }, { a: 3 }] // ✅

This is not allowed:

[{ a: 1 }, { a: 1 }, { a: 3 }] // ❌ Duplicated 1
[{ a: true }, { a: "nice" }, { a: true }] // ❌ Duplicated true
2

2 Answers 2

2

No, you cannot enforce such a restriction in TypeScript by creating a custom type. TypeScript only provides type-checking at compile time, and does not perform value-based checks. You will have to implement such validation logic yourself in your code.

Sign up to request clarification or add additional context in comments.

2 Comments

Well, if the exact type of the array is known, then it can perform the check.
You're right, but in simple terms answer is no. Actual check for uniqueness will have to be done at runtime. It's possible to write complex validation logic. However, adding such logic to TypeScript types goes against its primary purpose of just providing type checking
2

I faced this issue a lot in my early days of Typescript. I think you might be interested in Maps. Also keep in mind this is TypeScript and "type" is very important in contrast to Javascript. I didn't see types in your example, so I was little unclear on what you want. Here's an example using Maps that might help or give you some ideas. Of course you can also create your own class for this, which would allow for whatever you want. And take advantage of Typescript by providing types. It's annoying at first but really helps.

class MyObject {
  a: number
}
let myArray:MyObject[] = []

let a = new Map()
a.set('1',true)
a.set('2',true)
a.set('3',true)
a.set('1',true)

a.forEach( (value,key) => {
  let obj = new MyObject()
  obj.a = value
  myArray.push(obj)
})

console.log(myArray)

Which would display:

(3) [MyObject {...}, MyObject {...}, MyO...]
0: MyObject {a: "1"}
1: MyObject {a: "2"}
2: MyObject {a: "3"}

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.