似乎有時即使存在類型警衛,TypeScript(最近版本)仍未能縮小聯合類型。 這種行爲是錯誤或功能:TypeScript聯合類型推斷失敗
序言:
// some config
interface Config {
name: string;
option1?: number;
option2?: boolean;
}
// arbitrary type
interface Entity {
a: number;
b: number;
}
// name aware type guard for entity property-to-config map
// some default config may be replaced with a property name
type TConfigSet<TData> = {
[P in keyof TData]: (Config & { name: P }) | P;
}
// example of TConfigSet usage
const EntityConfigs: TConfigSet<Entity> = {
a: {
name: 'a',
option2: true
},
b: 'b'
}
問:
// this function compiles
function TypeLooseFieldToName(name: string | Config): string {
if (typeof name === 'string') return name;
else return name.name;
}
// this one doesn't
function TypeStrictFieldToName<TData>(name: keyof TData | { name: keyof TData }): keyof TData {
if (typeof name === 'string') return name;
else return name.name; // still keyof TData | { name: keyof TData }, should be shrinked to { name: keyof TData }
}
你是正確的,這是固定在2.6中的錯誤 –