簡體   English   中英

Typescript 接口未知鍵名

[英]Typescript Interface with unknown key name

我試圖在 Typescript 中創建一個接口,該接口具有未知鍵名和已知鍵名。 像這樣的東西:

interface Data { 
    test: string,
    [key: string]: string,
    foo?: boolean,
}

所以我能夠做到這一點:

x: Data = {
  test: "test_string",
  "unknown_key": "value"
}

任何人都知道我怎么能做到這一點? 謝謝。

一種方法是將自定義字段與Record<string, string>結合起來:

type Data = Record<string, string> & { 
  test: string;
  foo?: boolean;
}

這里有一個例子:


// You can omit `test` property in Data interface since it has a string type
interface Data { 
    [key: string]: string,
    foo?: boolean,
}

// You can use Verify helper instead of Data interface. It is almost the same
type VerifyT<T> = { foo?: boolean } & { [K in keyof T]: K extends "foo" ? unknown : string };

const make = <T extends VerifyT<T>>(t: T) => t;
make({ age: 'sdf', foo: true }) // Ok
make({ age: 'sdf', foo: undefined }) // ok
make({ age: 'sdf', foo: undefined }) // false
make({ age: 'sdf', foo: 'some text' }) // error
make({ age: 'sdf', foo: 1 }) // error
make({ age: 'sdf', foo: [1] }) // error

不用擔心 function 開銷,因為如果你使用 V8 引擎,它將被 99% 內聯和優化

所有的功勞都歸於這個答案。

也可以隨意將此問題標記為重復

暫無
暫無

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

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