microsoft / microsoft/typespec

Support `self` or `this` for referencing members

Open
#8,765 0 comments 0 reactions 0 assignees View on GitHub
compiler:core design:needed triaged:core
Dominant language
Java
Stars
5.9k
Forks
394
Avg merge
1d 23h
Merged PRs (30d)
104

Description

## Problem
While doing this PR https://github.com/microsoft/typespec/pull/8751 to fix some cases where we wrongly didn't instantiate types this uncovered a pattern that was kinda allowed before(though failing if you actually used it)

If an templated interface operation reference another operation in that interface then it would actually reference the interface declaration not the same instance. It somwhow kinda works when the parmaeter wasn't used but would get a crash as it would keep some TemplateParameter type in the type graph

[playground](https://typespec.io/playground/?e=%40typespec%2Fopenapi3&c=aW50ZXJmYWNlIEJhc2U8QT4gewogIERlZmF1bHQgaXPFFy5DdXN0b208QT47CgogIMcOVD4oYTogQSk6IFQ7Cn0KCspLVGVzdCBleHRlbmTGQTxzdHJpbmc%2BIHt9&options=%7B%7D&vs=%7B%7D)
```tsp
interface Base {
Default is Base.Custom
;

Custom(a: A): T;
}

interface Test extends Base {}
```

## Proposal

Introduce a `self` or `this` that reference to the current instance, the above could be rewritten as
```tsp
interface Base
{
Default is self.Custom
;

Custom(a: A): T;
}
```

Things to figure out what does it means with spread or inheritance like

```tsp
model Base {
id: string;
extId: self.id;
}

model Case1 extends Base {
id: uuid;
}

model Case2 {
...Pick
id: uuid;
}
```

is extId string or uuid here

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.