ts-morph icon indicating copy to clipboard operation
ts-morph copied to clipboard

[Question] How to create a TypeLiteral ?

Open igorissen opened this issue 3 years ago • 1 comments

Hello,

I'm trying to create a TypeAliasDeclaration with a TypeLiteral for the type attribute but it receives only a string or a function as value.

This an example of what I want to create

export type Options = {
  port?: number;
  host?: string;
};

This is what I have currently

sourceFile.addTypeAlias({
  type: '{ port?: number; host?: number; }',
  name: 'Options',
  isExported: true,
});

Is there another way to achieve that ?

Screenshot 2022-09-28 at 22 09 23

By doing something like this

sourceFile.addTypeAlias({
  type: new TypeLiteral({
    propertySignatures: [
      new PropertySignature({ hasQuestionToken: true, type: SyntaxKind.NumberKeyword, name: 'port' }),
      new PropertySignature({ hasQuestionToken: true, type: SyntaxKind.StringKeyword, name: 'host' }),
    ]
  }),
  name: 'Options',
  isExported: true,
});

Thanks.

igorissen avatar Sep 28 '22 20:09 igorissen

Did you get an answer? I have a similar requirement.

jimblackler avatar Nov 03 '23 12:11 jimblackler