Home > front end >  How to create a typescript type for an array with unique properties for one key?
How to create a typescript type for an array with unique properties for one key?

Time:02-01

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

CodePudding user response:

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.

CodePudding user response:

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"}

  • Related