0

In the below syntax,

interface IPerson{
    firstName: string;
    lastName?: string;
}

const personList = [
    "p1": {firstName: "F1", lastName: "L1"},
    "p2": {firstName: "F2"},
    "p3": {firstName: "F3"}
];

// or

const personList = [
    {"p1": {firstName: "F1", lastName: "L1"}},
    {"p2": {firstName: "F2"}},
    {"p3": {firstName: "F3"}}
];

personList is an array of key:value pairs, where key is of type string and value is of type IPerson

Edit:

Below syntax allows more than one key:value pair at an index of an array

const personList:{[key:string]:IPerson}[] = [
    {
     "p1": {firstName: "F1", lastName: "L1"},
     "p2": {firstName: "F1", lastName: "L1"}   
    },
    {"p2": {firstName: "F2"}},
    {"p3": {firstName: "F3"}}
];

How to explicitly type personList?

3
  • 1
    First example of const personList is not a valid JS array. Commented Apr 27, 2018 at 15:27
  • @BlackBeard you are right. thank you Commented Apr 27, 2018 at 15:30
  • Both posted answers are as good as you're going to get, there's no way in the type system to constrain an object to a single property. Commented Apr 27, 2018 at 20:46

3 Answers 3

3
const personList: { [key: string]: IPerson }[]  = [
    {"p1": {firstName: "F1", lastName: "L1"}},
    {"p2": {firstName: "F2"}},
    {"p3": {firstName: "F3"}}
];

Define it as an array of objects whose key is a string and whose value is of type IPerson

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

1 Comment

There is a problem with your syntax. Edited
1

An index type cannot be constrained to a single property, so both the posted answers are probably as good as you'll get.

As an alternative you could use a tuple type:

const personList: [string, IPerson][] = [
    ["p1", { firstName: "F1", lastName: "L1" }],
    ["p2", { firstName: "F2"}],
    ["p3", { firstName: "F3" }]
];

This will constrain each element of the array to an array of [string, IPerson]:

personList.forEach(item => {
    const [key, person] = item;
    // `key` is type string (p1, p2, p3...)
    // `person` is type IPerson
});

4 Comments

Can't I have first element as key?let personList: [[id: string], IPerson][] = [] Because having keys in personList is most important
No. Array uses index, object uses keys.
you mean tuple is a n element array?
Basically, yes, it describes an array with known types at explicit indices.
0

You can create a map interface:

interface Map<T> {
    [K: string]: T;
}

const personList: Map<IPerson> = [];

1 Comment

Your syntax also has same problem. Query already edited. map<IPerson>[] does not work

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.