简体   繁体   English

Typescript 接口未知键名

[英]Typescript Interface with unknown key name

Im trying to create an interface in Typescript which has an both Unkown key names and known key names.我试图在 Typescript 中创建一个接口,该接口具有未知键名和已知键名。 Something like this:像这样的东西:

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

So that im able to do this:所以我能够做到这一点:

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

Anyone know how im able to do this?任何人都知道我怎么能做到这一点? Thanks.谢谢。

One way to do this is by combining the custom fields with Record<string, string> :一种方法是将自定义字段与Record<string, string>结合起来:

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

Here you have an example:这里有一个例子:


// 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

Don't worry about function overhead, because if you use V8 engine, it will be 99% inlined and optimized不用担心 function 开销,因为如果你使用 V8 引擎,它将被 99% 内联和优化

All gredits goes to this answer.所有的功劳都归于这个答案。

Also feel free to marks this question as a dublicate也可以随意将此问题标记为重复

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM