Home > Blockchain >  Type TypeB should re use Interface InterfaceA
Type TypeB should re use Interface InterfaceA

Time:08-05

I have a following TypeScript code.

interface InterfaceA {
  id: string;
  key: string;
  value: string | number;
}

type TypeB = null;

const sample: TypeB = { id: '1' };

I need few simple and maintainable solutions where TypeB should reuse InterfaceA to correctly implement const example: B = ....

I tried below which works fine but I am not sure if this is the best and maintainable approach.

interface InterfaceA {
  id: string;
  key: string;
  value: string | number;
}

type TypeB = InterfaceA & null;

const sample: TypeB = { id: '1' } as TypeB;

How can I do this in more than one approach?

CodePudding user response:

I think what you are looking for is the Partial utility type to make the properties of InterfaceA optional. This might be better than just using an intersection of null.

interface InterfaceA {
    id: string;
    key: string;
    value: string | number;
}

type TypeB = Partial<InterfaceA>;

const sample: TypeB = { id: '1' };

CodePudding user response:

Ok, let's start by understanding how null works in Typescript.

Typescript has two very different ways of handling null and undefined. If --strictNullChecks is true, then null and undefined are both essentially literal types, types whose only member is null or undefined respectively. If --strictNullChecks is false then null and undefined are members of every type.

Next let's explain intersection types type T = A & B means that for a value to be of type T it must be of both type A and type B. So {a:string} & {b:string} is {a:string, b:string}. Intersections of non interface types are basically nonsense. What is string & number? No value is both a string and a number, so no value satisfies the type.

Ok, now let's look at your code type TypeB = null aliases the null type. Then const sample: TypeB = {id: '1'} is invalid Typescript. It won't compile, because an object is not null.

In your second example type TypeB = InterfaceA & null depends on the compiler settings. With strict null checks on TypeB is InterfaceA, with them off it is null. I leave it as an exercise to figure out why that is. In either case it doesn't do anything. The only reason your code compiles is that you use as TypeB. Typescript type assertions are unsafe. You can cast any type to any type. Which is why as should only be used in very narrow cases (mostly dealing with genuinely unknown data, like that coming from a serialization function).

So in the end, it's not at all clear what you want to do, but your code as written makes no sense, and you should probably spend some time reading the Typescript docs.

  • Related