Skip to content

Ability to create a type from an inferred type and reuse it #13949

Closed
@benstevens48

Description

@benstevens48

First of all, apologies if this is already possible or has already been suggested.

I'm a bit lazy when it comes to front-end development, so the type inference provided by TypeScript is very useful to avoid having to define interfaces etc.

However, sometimes I know that an object is of the same type as (or an extension of) another object but there's no way for the compiler to know. Therefore it would be useful for me to be able to save an inferred type for later reuse.

For example, I use VueJS components. To do this I need to provide a component options object which contains a methods object and a data function which returns the data. For example

function createData(){
  return {
    dataProp1: <string>null
  }
}

function method1(){
  let self = this;
  console.log(self.dataProp1);
  self.method2();
}

function method2(){
  let self = this;
  //dostuff
}

let componentOptions = {
  data: createData,
  methods: {method1, method2}
}
//todo: register component...

The self in the above code has the any type, but I as the developer know that the contents of methods and the result of create data will will available on this type. So it would be great it I could do something like this.

function createData(){
  return <=MyData>{
    dataProp1: <string>null
  }
}

function method1(){
  let self: MyComponent = this;
  console.log(self.dataProp1);
  self.method2();
}

function method2(){
  let self: MyComponent = this;
  //dostuff
}

interface MyComponent extends MyData, MyMethods {};

let componentOptions = {
  data: createData,
  methods: <=MyMethods>{method1, method2}
}
//todo: register component...

I'm not sure about the syntax but the =MyType is meant to mean that instead of requiring the object to be an instance of that type, it defines a new type MyType equal to the inferred type of the object. (The syntax should also work if I'd used let, as in, let methods: =MyMethods = {method1, method2}, instead of the angle brackets). Then I would have intellisense and type checking.

Apologies again if this is already possible or has already been suggested. I just thought I'd suggest it in case it was a good idea.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs InvestigationThis issue needs a team member to investigate its status.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions