Languages

TypeScript - is it possible to create object using new Record<Key, Value>() syntax?

5 points
Asked by:
Palus-Bear
1016

As in the question name: is it possible to create object using new Record<Key, Value>() syntax in TypeScript?

As I know, I am able to create object using const object = new Object(); syntax. But... what if I would like to use generic object? The first idea that I get is to use new Record<Key, Value>() syntax, but it doesn't work.

Any idea how to solve the problem?

1 answer
3 points
Answered by:
Palus-Bear
1016

You should define generic interface and contructor for Record<K, V>.

You can use this approach:

interface RecordConstructor {
    <K extends keyof any, V>(object: Record<K, V>): Record<K, V>;
    new <K extends keyof any, V>(object: Record<K, V>): Record<K, V>;
}

const Record: RecordConstructor = Object as RecordConstructor;


// Usage example:

const a                         = new Record<string, number>({name: 1});
const b: Record<string, number> =                            {name: 1} ;
const c: Record<string, number> = new Record<string, number>({name: 1});

const d                         =     Record<string, number>({name: 1});
const e: Record<string, number> =     Record<string, number>({name: 1});


// Constructor test:

const source = {name: 1};

const object1 = new Object(source);
const object2 = new Object(source);

const record1 = new Record<string, number>(source);
const record2 = new Record<string, number>(source);

console.log(object1 === source);  // true
console.log(object2 === source);  // true
console.log(record1 === source);  // true
console.log(record2 === source);  // true

Source: https://dirask.com/snippets/DnvYbD

 

See also

  1. TypeScript - create new Record<Key, Value>() using constructor (new operator) - example 1

  2. TypeScript - create new Record<Key, Value>() using constructor (new operator) - example 2

0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join