interface Example {
value?: string
[prop: string]: any
}
const xxx: Example = { name: 'Thomas' }
const v = xxx.name
在此处添加“ any”实际上会删除推断出的“ string”类型的名称,如果没有将xxx
分配给Example,则该名称将存在。
有没有办法让接口或类型传递推断的类型?
答案 0 :(得分:0)
这可以使用通用的Record
类型来完成:
type Example<K extends PropertyKey, V> = Record<K, V> & {
// non-generic interface properties go here
value?: string
};
const xxx: Example<'name', string> = { name: 'Thomas' };
const b = xxx.name; // ok, inferred as string
const x = xxx.address; // not ok
为避免必须在Example<'name', string>
中编写显式类型参数,可以使用通用标识函数:
function example<K extends PropertyKey, V>(e: Example<K, V>): Example<K, V> {
return e;
}
const xxx = example({ name: 'Thomas' });
将根据需要推断常量xxx
的类型为Example<'name', string>
。
答案 1 :(得分:0)
您可以将通用类型与联合使用:
type WithName<T> = T & { name?: string };
const myThing: WithName<{ foo?: string; bar?: number }> = { name: 'sup'};
答案 2 :(得分:0)
interface DictionaryLike {
[index: string]: unknown
}
interface Example extends DictionaryLike {
name: string;
}
const xxx: Example = { name: 'Thomas' }
const v = xxx.name; // string
const w = xxx.foo; // unknown