簡體   English   中英

使用 typescript 接口/類型限制訪問 toString

[英]Restrict accessing toString using typescript interface/type

我想要一個這樣的界面:

export interface Point {
  readonly x: number;
  readonly y: number;
  readonly toString: never;
}

我認為它會像這樣工作:

const p: Point = {x: 4, y: 5}; // OK
p.toString(); // triggers typescript error

但是我在第一行也得到了這個錯誤:

TS2322: Type '{ x: number; y: number; }' is not assignable to type 'Point'.
Types of property 'toString' are incompatible.
Type '() => string' is not assignable to type 'never'.

是否有一個選項可以在某些接口上限制 toString 的使用,而無需編寫類型斷言,例如const p: Point = {x: 4, y: 5} as Point; 到處?

我的用例:我目前正在重寫以前的內容

class Point {
    x: number;
    y: number;
    toString() {
        return `${x} ${y}`;
    }
}

將 object 與伴隨功能接口:

interface Point {
    x: number;
    y: number;
}
function pointToString({x, y}: Point) {
    return `${x} ${y}`;
}

我想在舊代碼庫中調用point.toString()會觸發錯誤,因為它們目前沒有,因為 JS 中的每個 object 都有一個toString()方法。

我能夠使用unknown類型進行此操作:

type NullPrototype = Record<keyof Object, unknown>;

interface Point extends NullPrototype {
  readonly x: number;
  readonly y: number;
}

const p: Point = {x: 4, y: 5}; // OK
p.toString(); // TS error: Object is of type 'unknown'.

我稱它為NullPrototype是因為它本質上是 vanilla JS 中這種模式的類型級版本:

const p = Object.create(null); // TS infers type `any`
p.x = 4;
p.y = 5;
p.toString(); // Fails at runtime, but passes type check???

是關於 TypeScript GitHub 的相關問題,盡管我認為那里沒有人想出這個特定的解決方案

暫無
暫無

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

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