nouvist
nouvist

Reputation: 1182

Typescript, object extends from interface and get its type

interface Hewan {
  type: string;
  name: string;
  age: number;
}

const createKucing = (name: string, age: number) => (
  {
    type: 'kucing' as const,
    name,
    age,
    miaw: true,
  } as ({} extends Hewan)
);

type Kucing = ReturnType<typeof createKucing>;

const isKucing = (x: unknown): x is Kucing => (x as Kucing).type === 'kucing';

I want to make an object constractor createKucing and also the interface of Kucing which is ReturnType of createKucing itself. So Kucing interface will change dynamically as soon as I change the constructor.

But I want the createKucing is extends from Hewan. So Hewan interface is kind of abstraction for Kucing. So, the type, name, and age is required when I make a constructor, but also I want to still can add property on it like miaw. Is that possible? I tried with assertion extends but it shows an error.

'?' expected.

I expect Kucing to have miaw property as I made it on constructor, but I want to the constructor is inherit from Hewan. Is that possible?

img

Upvotes: 0

Views: 66

Answers (2)

a2best
a2best

Reputation: 262

interface Hewan {
  type: string;
  name: string;
  age: number;
}

interface Kucing extends Hewan {
  type: 'kucing';
  miaw: boolean;
}

const createKucing = (name: string, age: number): Kucing => (...

Playground Link

Upvotes: 1

WebEXP0528
WebEXP0528

Reputation: 601

interface Hewan {
  type: string;
  name: string;
  age: number;
  [index:string]:any;
}

Upvotes: 1

Related Questions