0

Given a typescript interface:

interface alpha {
  name?: string;
  age?: string;
  sign?: string;
}

I would like to create another interface that is confined to have a limited set of properties from another interface

interface beta {
  age?: string;
}

Is this possible?

If someone was to have:

interface beta {
  foo?: string;
}

I'd like it to be invalid.

1 Answer 1

2

Great answer here: How to remove fields from a TypeScript interface via extension

So you make a "helper type" called e.g. Omit to omit certain properties from your interface:

type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>

Likewise, you can also modify the properties of your existing interface, which can be useful many times:

type Readonly<T> = {
    readonly [P in keyof T]: T[P];
}
type Partial<T> = {
    [P in keyof T]?: T[P];
}

Also, sometimes it's easier to turn it around. Extend alpha from beta.

interface alpha extends beta {
  name?: string;
  sign?: string;
}

interface beta {
  age?: string;
}

const x: alpha = {
    name: "foo" // valid
}

const y: beta = {
    name: "where" // invalid
}
Sign up to request clarification or add additional context in comments.

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.