0
interface IType {
    name: string;
    label: string;
    checked?: boolean;
    disabled?: boolean;
}
interface Category {
    name: string;
    label: string;
    description: string;
}
type Data = Array<{
    name: string;
    label: string;
    description: string;
    types: IType[];
}>;

I have the above type descriptions. If you see the interface Category has same three keys as in type Data. How can I refer the interface Category inside my type Data without duplicating as I am doing above. Please note that I do not want additional key in my type Data.

Thanks

2 Answers 2

3

Introduce a named interface for the content of the array, which extends Category:

interface IType {
    name: string;
    label: string;
    checked?: boolean;
    disabled?: boolean;
}
interface Category {
    name: string;
    label: string;
    description: string;
}

interface DataItem extends Category {
    types: IType[];
}

type Data = Array<DataItem>;
Sign up to request clarification or add additional context in comments.

1 Comment

Definitely this, not least because it makes Data largely unnecessary; the OP could just use DataItem[].
3

The minimal change is to use an intersection type:

type Data = Array<Category & {
// −−−−−−−−−−−−−−−^^^^^^^^^^
    types: IType[];
}>;

Live Example

...but I'd suggest following JB's advice and creating a type for the contents of that array.

I'd also probably shy away from having a Data type at all, but that's a matter of style. If you use a type for the content, you can just use ThatType[] where you're currently using Data.

4 Comments

I was going to ask you if you preferred your solution to mine. Except maybe simplicity, is there any advantage or drawback with your/my suggestion?
@JBNizet - I'm not a TS expert, but for me your solution is better because it means the OP can just use DataItem[] and not even bother with a Data type (unless they prefer it for style reasons). I'm sure both have a place, but without more info, I'd go your way. :-)
Thanks a lot @T.J. I'm not a TS expert either. I like it a lot more than JavaScript, but its type system is way more complex than anything else I've used.
I just wanted to look fancy lol using type. Thanks both solution works.

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.