![](/img/trans.png)
[英]Typescript interface where key name has known prefix but full key is unknown
[英]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.