โŒ

Normal view

There are new articles available, click to refresh the page.
Before yesterdayMain stream

How to create selector with parameters like in NGRX signalStore like `createSelector` in NGXS?

I'm refactoring the code and I started to moving code to the signalStore, but I was stuck while creating custom selector with some property to make it like signal computed value.

NGXS Code:

interface Permission { 
   name: string;
}

interface UserStateModel {
   permissions: Permission[];
}

const DEFAULT_STATE: UserStateModel= {  
    permissions: []
};

@State<UserStateModel>({
    name: 'user_state',
    defaults: DEFAULT_STATE,
})
@Injectable()
export class UserState {
    @Selector()
    static permissions(state: UserStateModel): Permission[] {
        return state.permissions;
    }

    static permission(spermissionName: string) {
       return createSelector(
           [UserState.permissions], 
           (permissions) => permissions.find(x => x.name === permissionName)
        })

     }
}

As you can see, I can use UserState.permission('myPermissionName') and do any action if this position change.

export type UserStoreModel = {
    permissions: Permission[;
};

const DEFAULT_STATE: UserStoreModel = {
    permissions: [],
};

export const UserStore = signalStore(
    withState(DEFAULT_STATE),
    withComputed(store => {
        return {
            permissions: computed(() => store.permissions() ?? []),
        };
    }),
);

It should be a method which return Signals? Maybe there is something like createSelector which I can use here with Signals?

Thanks for help.

I did a research but I can't find any valid solution for this.

I'm expecting I will be able to make selector with Signals using ngrx signalStore.

Example usage of this:

/// My view

const hasAccessPermissions = computed(() => {
   const result = this.userStore.hasAccess('MyPermission');   //<--- this should be reactive
   return result;
});

private readonly userStore = inject(UserStore);

How to use .js and .d.ts files in project

having this some.js file

export function myFunc(a, b) {
  return a.asdf + b;
}

I want to be able to write something like this let's say in some.d.ts file

export declare function myFunc(a: number, b: number): number;

then run 'npx tsc' command which will give me 'asdf is not a member of type number', but right now i get errors saying "parameter a implicitly has any type". I have this tsconfig.json

{
  "compilerOptions": {
    "allowJs": true,
    "checkJs": true,
    "noEmit": true,
    "strict": true,
    "skipLibCheck": false,
  },
  "include": ["**/*.js", "**/*.d.ts"]
}

Is it that I miss some ts options or I should declare types in .d.ts differently? If it is impossible, what is the general way to program in js but having typings and not in one global.d.ts file?

I also tried

declare namespace some {
  export function myFunc(a: number, b: number): number;
}

and

declare module "some" {
  export function myFunc(a: number, b: number): number;
}

I am having an issue with github actions. It says ' has no call signatures." after building up my TS to JS

I am new to CI/CD via github actions. I have a node typescript project and I have create some basic steps like jest testing, docker image etc. The issue is that during build up in my local machine typscrip create a dist folder with js code and work fine but not in github actions its look like dist folder contains ts code instead of js. Please help

Yaml file: name: Build, Test, and Push

on: push: branches: [ main ]

jobs: build-test-push: runs-on: ubuntu-latest strategy: fail-fast: false # Allows all steps to run even if one fails

steps:
  - uses: actions/checkout@v3

  - name: Use Node.js
    uses: actions/setup-node@v3
    with:
      node-version: 16  # Adjust this version if needed
    
  - name: Install dependencies (production)
    run: npm ci --production  # Clearer command for production deps

  - name: Build project
    run: npm run build

  - name: Run tests
    run: npm test

  - name: Build Docker image and tag
    run: |
      docker build -t online_food_order_app-server .
      docker tag online_food_order_app-server harisbukhari/bitepal  # Adjust username and image name
  - name: Login to Docker Hub with access token (optional)
    run: docker login -u ${{ secrets.DOCKER_USERNAME }} -p ${{ secrets.DOCKER_ACCESS_TOKEN }}

  - name: Push Docker image (optional)
    run: docker push harisbukhari/bitepal  # Replace with your full repository name

Console: Please view the image

I have try changing yaml file but stil getting issues.

React RTK queryFn return type Typescript lint issue

I have following RTK query code where I'm using queryFn, the return type I what Im already returning but lint is showing me an error. Please note the code is working fine and even there are no console error when running application in browser.

        postExpenses: build.mutation<Expense[], Expense>({
            queryFn: async (data) => {
                const res = await serverApi.expenses.$post({ json: data })
                if (!res.ok) {
                    throw new Error("Server Error");
                }
                const result = await res.json();
                // even tried return result as Array<Expense>
                return result
            }
        })

Error in lint:


Type
{   id: number;   title: string;   amount: number; }[]

is not assignable to type
QueryReturnValue<Expense[], unknown, {} | undefined>

RTK queryFn ts type error

apiClient is Hono RPC enter image description here

Can't bind input when using abstract classes (2+ level of hierarchy)

In my Angular app:

  • When a Component uses an Input that is defined in its direct parent (abstract) class, everything works fine.

  • When a Component uses an Input that is defined in a 2-levels up parent (abstract) class, the ng build or ng serve give an error.

For example, I have 4 classes:

export abstract class AbstractAComponent {
  @Input() myInput: string;
}
export abstract class AbstractBComponent extends AbstractAComponent {}
@Component({
  selector: 'app-one',
  templateUrl: './one.component.html',
  styleUrls: ['./one.component.scss']
})
export class OneComponent extends AbstractAComponent {}
@Component({
  selector: 'app-two',
  templateUrl: './two.component.html',
  styleUrls: ['./two.component.scss']
})
export class TwoComponent extends AbstractBComponent {}

This is how I use them:

<app-one [myInput]="'value 1'"></app-one>
<app-two [myInput]="'value 2'"></app-two>

In a nutshell: - @Input() myInput is defined in AbstractAComponent - OneComponent directly extends AbstractAComponent - TwoComponent extends AbstractBComponent which extends AbstractAComponent

Expected behaviour: - both OneComponent and TwoComponent should have @Input() myInput

Current behaviour: - looks like TwoComponent doesn't correctly inherit @Input() myInput

and I got the following error:

ERROR in src/app/app.component.html:2:10 - error NG8002: Can't bind to 'myInput' since it isn't a known property of 'app-two'.
1. If 'app-two' is an Angular component and it has 'myInput' input, then verify that it is part of this module.
2. If 'app-two' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.

react-router-dom is not working for nested page and sub-pages for react application in sub-directory

I am working on react application using vite and I am using latest version of react-router-dom v 6.23.0. My react application is build on the subdirectory (./new-mobile/dist) of main directory.

Here is my main.tsx file

import ReactDOM from 'react-dom/client'
import App from './App'
import './index.css'
import store from '../redux/store.js'
import { Provider } from 'react-redux'
import {RouterProvider, createBrowserRouter} from 'react-router-dom';
import App3 from './App3'
import TestFile from './TestFile'

const basename = '/new-mobile/dist';

const router = createBrowserRouter([
  {
    path: '/',
    element: <App />,
    children: [
      {
        path: 'testfile',
        element: <TestFile />
      }
    ]
  },
  {
    path: 'app3',
    element: <App3 />
  }
],
{
  basename: basename
});

ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
  <Provider store={store}>
    <RouterProvider router={router} />
  </Provider>
);

And here is the vite.config.ts file

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import Checker from 'vite-plugin-checker';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    react(),
    Checker({ typescript: true }),
  ],
  base: './new-mobile/dist'
})

The main problem is when i am going on home page https://my-domain/new-mobile/dist it it working correctly, but when I go to its nested page (https://my-domain/new-mobile/dist/testfile) or child/sub-page like (https://my-domain/new-mobile/dist/app3) it breaks outs.

Also, this router is working fine on my local setup but breaks on test environment.

Things I tried: I tried adding basename but is is also not working. I tried jsx version of router, but still not working.

when I try to access /app3, this comes. broser image

DDD Identifier, autoincrement ID and UUID

I'm developing web application project in Typescript while learning and applying DDD (domain driven design) at the same time.

In our database we use autoincrement ID's for the primary keys. But this approach is something means that no ID will be ready until an entity is persisted.

In DDD every entity that is created should have its identifier from start, so what happens when an entity is created before it is saved to the database? (for example it is created in the frontend). Then, no ID will be available.

In DDD as well its said that every value that is not a entity should be a Value Object, hence the identifier should be a value object as well.

With those premises, I thought of a UniqueEntityID value object that will do the following:

  • The UniqueEntityID hold 2 attributes, uuid and autoincrementId.
  • When the ID is created, if no value is passed to the contructor, it will use a randomly generated uuid, but if a value is give, it will be the autoincrement of the database.
  • To get the real value of the ID, there's a value getter, that will provide the autoincrementId if it exists or the uuid if not.

This way, whenever the entity is retrieved from the repository it will come with the autoincrementId as the value, but to the newly created entities, it will use the UUID. At the moment of saving an entity, if the ID is not persisted it is removed from its attributes, so the new entity is created in the database.

Please tell me if this approach is correct, or if it is an anti pattern, or if I'm missing something.

This is the code used for the UniqueEntityID.

class UniqueEntityID {
  private readonly uuid: string
  private readonly autoincrementId: number

  /**
   * Creates an identifier using UUID implementation,
   * used when the entity is not yet persisted.
   */
  constructor()
  /**
   * Creates an identifier using the autoincrement ID
   * from the database.
   * @param id - The ID given from a database autoincrement.
   */
  constructor(id: number)
  constructor(id?: number) {
    if (typeof id === 'undefined') {
      this.uuid = v4()
    } else {
      this.autoincrementId = id
    }
  }

  /**
   * Check if the ID is an autoincremented ID generated by
   * the database
   */
  get isPersisted() {
    return typeof this.autoincrementId !== 'undefined'
  }

  /**
   * The value of the ID.
   */
  get value() {
    return this.autoincrementId ?? this.uuid
  }
}

Best regards, Jorge

HighChart (area) change series color dynamically inTypeScript

How to change HighChart (area3D) series color in react TypeScript? series data will be chage with setData() but i get this error " TS2304: Cannot find name 'SeriesOptionsType'. " while trying to change series color using chart.series[i].update(SeriesOptionsType,true).

    componentDidUpdate(prevProps: Readonly<ComponentProps<AreaChartProps>>, prevState: Readonly<any>, snapshot?: any) {
        if (this.chartRef.current){
            const chart = this.chartRef.current.chart as Chart;
            for ( let i:number =0 ; i < chart.series.length ; i++){
                chart.series[i].setData(this.props.props.series[i].data,true,true,true);

                chart.series[i].color = this.props.props.series[i].color
                chart.series[i].update(SeriesOptionsType,true)
            }
        }else {
            console.log( "error chart reference not available")
        }
    }

and also get this error "TS2339: Property 'color' does not exist on type 'SeriesOptionsType'. ย ย Property 'color' does not exist on type 'SeriesTiledwebmapOptions'." when using below code

chart.series[0].options.color = "#008800";
chart.series[0].update(chart.series[0].options);

I searched all the net, but i didn't find anything about changing the color using typescript. Also i'm new to scripting languages

Type 'undefined' is not assignable to type 'ApexAxisChartSeries | ApexNonAxisChartSeries'

I have used this code in ts

export type pieChartOptionss = {
  series?: ApexNonAxisChartSeries | '';
  chart?: ApexChart | '';
  legend?: ApexLegend | '';
  dataLabels?: ApexDataLabels | '';
  responsive?: ApexResponsive[] | '';
  labels?: any | '';
};
export class DashboardComponent implements OnInit {
 public pieChartOptionss!: Partial<pieChartOptionss>;
}
     (response: any) => {
          this.user_data = response.results;
          console.log('user_data', this.user_data)
          this.user_data_true = this.user_data.filter(x => x.is_active === true)
          this.user_data_false = this.user_data.filter(x => x.is_active === false)
          this.pieChartData = [this.user_data_true.length, this.user_data_false.length];
          this.pieChartOptionss = {
            series: [this.user_data_true.length, this.user_data_false.length],
            chart: {
              type: 'donut',
              width: 270,
            },
            legend: {
              show: false,
            },
            dataLabels: {
              enabled: true,
            },
            labels: ['Active', 'Inactive'],
            responsive: [
              {
                breakpoint: 480,
                options: {},
              },
            ],
          };
        }

and in html I have used this code:

    <div class="body" *ngIf="pieChartOptionss">
          <apx-chart [series]="pieChartOptionss?.series" [chart]="pieChartOptionss?.chart"
            [labels]="pieChartOptionss?.labels" [responsive]="pieChartOptionss?.responsive"
            [dataLabels]="pieChartOptionss?.dataLabels" [legend]="pieChartOptionss?.legend" class="apex-pie-center">
          </apx-chart>
          <div class="table-responsive m-t-15">
            <table class="table align-items-center">
              <tbody>
                <tr>
                  <td><i class="fa fa-circle col-cyan mr-2"></i> {{ "active" | translate }}</td>
                  <td class="col-blue">{{pieChartOptionss?.series[0]}}</td>
                </tr>
                <tr>
                  <td><i class="fa fa-circle col-green mr-2"></i>{{ "inactive" | translate }}</td>
                  <td class="col-green">{{pieChartOptionss?.series[1]}}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

The problem is, when I ng serve project show this error:

ERROR in src/app/panel/dashboard/dashboard.component.html:97:26 - error TS2322: Type '"" | ApexNonAxisChartSeries | undefined' is not assignable to type 'ApexAxisChartSeries | ApexNonAxisChartSeries'.
Type 'undefined' is not assignable to type 'ApexAxisChartSeries | ApexNonAxisChartSeries'.

97 <apx-chart [series]="pieChartOptionss?.series" [chart]="pieChartOptionss?.chart" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

src/app/panel/dashboard/dashboard.component.ts:93:16 93 templateUrl: './dashboard.component.html', ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Error occurs in the template of component DashboardComponent. src/app/panel/dashboard/dashboard.component.html:97:62 - error TS2322: Type '"" | ApexChart | undefined' is not assignable to type 'ApexChart'. Type 'undefined' is not assignable to type 'ApexChart'.

97 <apx-chart [series]="pieChartOptionss?.series" [chart]="pieChartOptionss?.chart" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

src/app/panel/dashboard/dashboard.component.ts:93:16 93 templateUrl: './dashboard.component.html', ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Error occurs in the template of component DashboardComponent. src/app/panel/dashboard/dashboard.component.html:98:53 - error TS2322: Type '"" | ApexResponsive[] | undefined' is not assignable to type 'ApexResponsive[]'. Type 'undefined' is not assignable to type 'ApexResponsive[]'.

98 [labels]="pieChartOptionss?.labels" [responsive]="pieChartOptionss?.responsive" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

src/app/panel/dashboard/dashboard.component.ts:93:16 93 templateUrl: './dashboard.component.html', ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Error occurs in the template of component DashboardComponent. src/app/panel/dashboard/dashboard.component.html:99:17 - error TS2322: Type '"" | ApexDataLabels | undefined' is not assignable to type 'ApexDataLabels'. Type 'undefined' is not assignable to type 'ApexDataLabels'.

99 [dataLabels]="pieChartOptionss?.dataLabels" [legend]="pieChartOptionss?.legend" class="apex-pie-center"> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

src/app/panel/dashboard/dashboard.component.ts:93:16 93 templateUrl: './dashboard.component.html', ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Error occurs in the template of component DashboardComponent. src/app/panel/dashboard/dashboard.component.html:99:61 - error TS2322: Type '"" | ApexLegend | undefined' is not assignable to type 'ApexLegend'. Type 'undefined' is not assignable to type 'ApexLegend'.

99 [dataLabels]="pieChartOptionss?.dataLabels" [legend]="pieChartOptionss?.legend" class="apex-pie-center"> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

src/app/panel/dashboard/dashboard.component.ts:93:16 93 templateUrl: './dashboard.component.html', ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Error occurs in the template of component DashboardComponent. src/app/panel/dashboard/dashboard.component.html:106:46 - merror TS2532: Object is possibly 'undefined'.

106 {{pieChartOptionss?.series[0]}} ~~~~~~~~~~~~~~~~~~~~~~~~~~~

src/app/panel/dashboard/dashboard.component.ts:93:16 93 templateUrl: './dashboard.component.html', ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Error occurs in the template of component DashboardComponent. src/app/panel/dashboard/dashboard.component.html:110:47 - error TS2532: Object is possibly 'undefined'.

110 {{pieChartOptionss?.series[1]}}

Is narrowing down a union type with optional chaining possible?

I have a discriminating union, simplified into this example.

type FoobarEvent = FooEvent | BarEvent;

interface FooEvent {
    type: 'foo';
    foo: {
        name: string;
    }
}

interface BarEvent {
    type: 'bar';
    bar: {
        id: string;
    }
}

Of course I can check the discriminant and get the union type narrowed down properly.

// let's assume this exists
declare const foobarEvent: FoobarEvent;

let fooName: string | undefined;

if (foobarEvent.type === 'foo') {
    fooName = foobarEvent.foo.name;
}

However I want to avoid this if-block, so I tried to use optional chaining to narrow down the type, but that doesn't work because one of the unions doesn't have the field I'm trying to access.

const fooNameByChaining = foobarEvent.foo?.name;

Property 'foo' does not exist on type 'FoobarEvent'.
ย Property 'foo' does not exist on type 'BarEvent'.

So apparently the narrowing would need to happen before the optional chaining. Is this a limitation of TypeScript's type system or could this be added to Typescript as a feature? Or is there another way around this that I'm not aware of?

Playground Link

jest and jose Uint8Array type mismatch

When running jest that calls the below function in jest unit test, I get multiple errors related to Uint8Array. I suspect what is happening is the implementation of the test environment's Uint8Array is different than the implementation within jose. When I use visual studio code to go to definition of Uint8Array within jest.setup.ts, it is different than the implementation in my source files, and also within jose package

import { SignJWT, jwtVerify, JWTVerifyOptions, JWTPayload } from 'jose'; //used for jwt
export async function get_jwt_token() {
    const sig = (new TextEncoder().encode('MYSECRETKEY543534')) as Uint8Array;
    const token = await new SignJWT()
        .sign(sig); //causes TypeError: payload must be an instance of Uint8Array in jest

    return token;
}

I also get a related error when calling jwtVerify Key for the HS256 algorithm must be one of type KeyObject or Uint8Array. Received an instance of Uint8Array

 try {
        const result = await jwtVerify(
            token,
            new TextEncoder().encode('MYSECRETKEY543534'),
            {
                algorithms: ['HS256'],
                maxTokenAge: '10 m',
            } as JWTVerifyOptions
        ); // Causes Key for the HS256 algorithm must be one of type KeyObject or Uint8Array. Received an instance of Uint8Array
        return result.payload as unknown as UserJwtPayload;
    } catch (err) {
        throw new Error(getErrorMessage(err));
    }
    it('get_jwt_token should not cause an error', async () => {
        const token = await get_jwt_token('admin', 'my-password');
        console.log(token);
    });

    it('verify_jwt should not cause an error', async () => {
        const token = await verify_jwt('my-token');
        console.log(token);
    });

Here is my jest.setup.ts

import { TextEncoder, TextDecoder } from 'util';
Object.assign(global, { TextDecoder, TextEncoder });

jest.config.js

const nextJest = require("next/jest");
const createJestConfig = nextJest({
    dir: "./",
});
const customJestConfig = {
    preset: "ts-jest",
    roots: ["<rootDir>"],
    modulePaths: ["<rootDir>", "<rootDir>/src"],
    moduleDirectories: ["node_modules"],
    setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
    testEnvironment: "jest-environment-jsdom",
    moduleNameMapper: {
        "^@src/(.*)$": "<rootDir>/src/$1",
    },
    testEnvironmentOptions: { 
        customExportConditions: [''],
    },
};
module.exports = createJestConfig(customJestConfig);

I am using the latest versions of jest and jose but also tried older versions. I expect it to work normally without error. I even tried console.log(sig) inside of get_jwt_token and it shows the type as Uint8Array during jest test so I am not understanding the problem.

Am I missing something? Any help would be appreciated, thank you.

Calling an authenticated google cloud API without an existing client library

I'm trying to deploy an application on GCP Marketplace and I'm struggling to understand the documentation for authentication. Based on the docs, an OAuth scope of https://www.googleapis.com/auth/cloud-platformis required with a link to the authentication docs, however those docs just tell you to "use one of the client libraries"

The API I'm trying to use is the partner procurement API, and while a node.js client exists at @google-cloud/procurement, the vast majority of the methods in the documentation relating to entitlements and accounts are not exposed as methods, with the only functions relating to what appears to be some kind of legacy "order" system. I'm also not sure if it's even the correct client library, as after checking the source code for it I can see the API host is cloudcommerceconsumerprocurement.googleapis.com instead of cloudcommerceprocurement.googleapis.com

Here are the APIs I wish to call: https://cloud.google.com/marketplace/docs/partners/commerce-procurement-api/reference/rest/v1/providers.entitlements

How can I call these APIs from a google cloud run service? Is there any way I can use google-gax to call these API endpoints with auth? Normally with the client libraries everything "just works" thanks to them reading auth from environment variables when running in GCP

How to declare "any" module in TypeScript?

I need to migrate step by step some large project from js to typeScript.

I rewrite on of the files in ts and i want to specify that other files at this moment can contain any content.

For example something like that:

declare module jsModule:any;
var obj:jsModule.cls = new jsModule.cls()

But it does not work in this moment. I need to specify each exported class/function/variable in module declaration.

Can i declare external module as "any" in some fast way?

I can't get my sam local start-api to work with Typescript

I can't for the life of me understand how I would set up SAM to run my Typescript/nodejs api locally.

I run sam local start-api and everything kind of starts up. Lots and lots of debug logging that doesn't tell me anything. Once I try to invoke the API endpoint with CURL I get the following error message:

26 Apr 2024 00:43:22,108 [ERROR] (rapid) Init failed error=Runtime exited with error: exit status 129 InvokeID=
26 Apr 2024 00:43:22,109 [ERROR] (rapid) Invoke failed error=Runtime exited with error: exit status 129 InvokeID=3506a416-5cd1-42a3-ba56-45ffa76d2369
26 Apr 2024 00:43:22,110 [ERROR] (rapid) Invoke DONE failed: Sandbox.Failure

Here's an example of how I set up a lambda function in the SAM template yaml:

  GetAuthenticatedUserDetailsFunction:
      CodeUri: ../
      Handler: GetAuthenticatedUserDetails.lambdaHandler
      Events:
        GetAuthenticatedUserDetails:
          Type: Api 
          Properties:
            RestApiId: !Ref api
            Path: /gaud
            Method: get
      Policies:
        - Version: '2012-10-17' 
          Statement:
            - Effect: Allow
              Action: "rds-db:connect"
              Resource: !Sub 'arn:aws:rds-db:${AWS::Region}:${AWS::AccountId}:dbuser:${DBProxyPRXID}/*'
    Metadata:
      BuildMethod: esbuild
      BuildProperties:
        Minify: true
        Target: es2020
        Sourcemap: true
        EntryPoints:
        - src/GetAuthenticatedUserDetails.ts

What am I doing wrong? I thought the sam cli would be smart enough to figure all this out by itself?

Here are some things that I already know

  • Entrypoints attribute contains the "src" directory. If I move that dir to the CodeUri attribute then sam build fails by saying that esbuild doesn't exist on my machine (but magically does exist with this config)
  • The sam build command transpiles all the .ts code to .js dirs in the ./aws-sam directory. But! It has a different structure where the code is compiled per function.

I understand that the error points to the fact that sam local can't find the function in whatever directory it is looking in. The Typescript code is transpiled into a .aws-sam/ directory that has a completely different structure (I assume it's self contained and will be zipped up for deployment).

I did try to hack the CodeUri attribute to point to the .aws-sam directory

What does it mean by "can be treated as the interface type" in TypeScript handbook?

In the handbook, it says that:

Itโ€™s important to understand that an implements clause is only a check that the class can be treated as the interface type. It doesnโ€™t change the type of the class or its methods at all. A common source of error is to assume that an implements clause will change the class type - it doesnโ€™t!

But I don't understand what it means by "can be treated as the interface type" when it also says "It doesnโ€™t change the type of the class or its methods at all."

Does it mean that I need to repeat the exact same types for both the class and the interface?

They give an example where the type of s is any:

interface Checkable {
  check(name: string): boolean;
}
 
class NameChecker implements Checkable {
  check(s) {
    // Notice no error here
    return s.toLowerCase() === "ok";
  }
}
โŒ
โŒ