簡體   English   中英

如何在 TypeScript 中正確更改變量的類型?

[英]How to properly change a variable's type in TypeScript?

感謝您的耐心等待,我剛剛開始使用 TypeScript。

我正在開發一個需要接受文本輸入然后進行大量計算的 angular 2 應用程序。 我(錯誤地?)假設我需要首先將輸入綁定到我的數據模型中的“任何”類型變量,然后將這些變量轉換為數字以處理數字。 我環顧四周,找不到如何以不會引發此 TS 編譯器錯誤的方式執行此操作:

`src/calculator_service.ts(40,5): error TS2322: Type 'number' is not assignable to type 'string'.`

在我的 CalculatorService 中,我有這個功能:

/*
 * Convert the object of strings recieved from the form into a clean object of integers
 */
n(model:ModelFields) {
    // Clone it
    this.numericModel = Object.assign({}, this.model);

    for (var prop in this.numericModel) {
        if (this.numericModel.hasOwnProperty(prop)) {

            // strip off all non-numeric charactersklj
            this.numericModel[prop] = this.numericModel[prop].replace(/\D/g,'');

            // convert to Any typescript type
            // this breaks the application, and still throws a compiler error. nope.
            // this.numericModel[prop] = this.numericModel[prop]:Any;

            // convert to Number type
            // this gives a typescript console error, but seems to still compile... 
            // ignoring this for now in order to meet deadline
            this.numericModel[prop] = +this.numericModel[prop];

        }
    }

    return this.numericModel;
}

和 ModelFields 定義(感謝 tarh!)

export class ModelFields { 
    constructor( 
        public fieldName: any, 
        public anotherField: any 
    ) 
    {} 
}

有任何想法嗎? 謝謝大家!

你無法在TypeScript中更改變量的類型,這只是為了制作相反的TS。 相反,您可以將變量聲明為“any”,這相當於JS中的經典“var”變量,無類型。

聲明變量后,您將無法重新鍵入它。 但是,您可以做的是聲明“any”,然后在您想要使用它時將其強制轉換,以便將其用作所需類型。

例如,這不會引發任何錯誤:

let a: any;

a = 1234;
(a as number).toExponential();

a = "abcd"; 
(a as string).substr(1, 4);

對於您的類,這也是正確的,沒有類型錯誤:

class ModelFields { 
    constructor( 
        public fieldName: any, 
        public anotherField: any 
    ) 

    //...
}

let model: ModelFields = new ModelFields(1, 2);

console.log(model.fieldName + model.anotherField);    // --> 3

model.fieldName = "a";
model.anotherField = "b";

console.log(model.fieldName + model.anotherField);    // --> ab

你的例子不夠清楚,但我猜你的問題是因為Typescript推理

var x = 3; // x is a number
x = "45";  // compiler error

但是,如果你這樣做:

var x : any = 3; // x can be anything
x = "45";

要么:

var x; // x is any forever
x = '45';  // x is still any

您可以在這些精彩的幻燈片文檔中找到更多詳細信息

希望這可以幫助一點......

面對類似的查詢類型並為我工作。

我的情況:

article Id來自路徑參數和API的字符串格式我以數字格式獲取數據。

如果我檢查!=,ES lint會拋出錯誤。 所以我使用Number()方法將字符串轉換為vanilla javascript中的數字。

const articleId = Number(this.route.snapshot.params['articleId']);

data.forEach((element, index) => {

    // console.log(typeof(element['id']), element['id']); 
    // 4, number
    // console.log(typeof(this.route.snapshot.params['articleId']), this.route.snapshot.params['articleId']);
    // 4, string (converted to number)

    if (element['id'] !== articleId) {
        //my implementation
     }
}

參考鏈接:

  1. https://gomakethings.com/converting-strings-to-numbers-with-vanilla-javascript/

您可以通過省略舊類型的屬性,然后重新添加它們來創建新類型。

這將無法正常工作。

interface DbItem {
 _id: Buffer
 date: number
}

interface JsItem extends DbItem {
 _id: string
}

但是您可以使用實用程序類型Omit來省略要更改的類型,然后將它們添加回來。

interface DbItem {
 _id: Buffer
 date: number
}

interface JsItem extends Omit<DbItem, '_id'> {
 _id: string
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM