How to implement a JS function pointer in Typescript

I have the following in Javascript:

var chartOptions = {
    chartType: settings.chartType,
}

chartOptions.func = function(chart) {
    chartOptions.fullChart = chart;
}

everything is working fine.

But I want to change this to TypeScript and be new, I'm not sure how to do it. Can someone please help? For example, there is no symbol for "func", but for "fullChart" - no, since this works in Javascript?

+4
source share
2 answers

You can fix your code by adding properties to chartOptions:

var chartOptions = {
    chartType: settings.chartType,
    func: null,
    fullChart: null
}

chartOptions.func = function(chart) {
    chartOptions.fullChart = chart;
}

How about converting your code to a class? This is a lot more TypeScript -y :)

class ChartOptions {
    public chartType;
    public fullChart;

    public func(chart: any) {
        this.fullChart = chart 
    }
}    

let chart = {};
let chartOptions = new ChartOptions();
chartOptions.func(chart);
+5
source

. , .

interface ChartOptions {
    chartType: string;
    func: (chart: any) => void;
    fullChart: any;
}

var chartOptions = {
    chartType: settings.chartType
} as ChartOptions

chartOptions.func = function(chart) {
    chartOptions.fullChart = chart;
}

, , ( , , ).

interface ChartOptions {
    chartType: string;
    func: (chart: any) => void;
    fullChart?: any;
}

var chartOptions: ChartOptions = {
    chartType: settings.chartType,
    func (chart: any) {
        this.fullChart = chart;
    }
}

, , , , , .

0

Source: https://habr.com/ru/post/1620112/


All Articles